package com.quanyan.place.service.impl;

import com.alibaba.druid.sql.visitor.functions.If;
import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.dubbo.rpc.Result;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.support.odps.udf.CodecCheck;
import com.fasterxml.jackson.databind.util.BeanUtil;
import com.google.common.collect.Lists;
import com.quanyan.api.APIResponse;
import com.quanyan.common.Plugin.Page;
import com.quanyan.common.Plugin.PageObj;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.enums.PlatformTypeEnum;
import com.quanyan.common.enums.SysParameterConfigEnum;
import com.quanyan.common.utils.*;
import com.quanyan.pay.enums.PayWayEnum;
import com.quanyan.place.biz.IBaseService;
import com.quanyan.place.constants.PlaceConstants;
import com.quanyan.place.entity.*;
import com.quanyan.place.entity.apireq.*;
import com.quanyan.place.entity.apiresp.RespPlaceGoodsCommonVo;
import com.quanyan.place.entity.apiresp.RespPlaceGoodsTypeVo;
import com.quanyan.place.entity.apiresp.RespPlaceGoodsVo;
import com.quanyan.place.entity.apiresp.RespSupplierVo;
import com.quanyan.place.entity.vo.DictPlaceDataVo;
import com.quanyan.place.entity.vo.PlacePrintVo;
import com.quanyan.place.enums.PayTypeEnum;
import com.quanyan.place.enums.PlaceErrorCodeEnum;
import com.quanyan.place.mapper.*;
import com.quanyan.place.service.*;
import com.quanyan.place.utils.PlaceUtil;
import com.quanyan.place.wrapper.PlaceOrderServiceWrapper;
import com.quanyan.sms.service.SmsService;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.ibatis.annotations.Param;
import org.bouncycastle.voms.VOMSAttribute;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.ThrowsAdvice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import scala.Int;
import sms.SmsApi;

import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.*;

/**
 * 场馆基础service实现
 * Created by yangyun on 16-6-6.
 */
@Service("placeGoodsService")
public class PlaceGoodsServiceImpl implements PlaceGoodsService {

    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    TbBizPlaceGoodsMapper tbBizPlaceGoodsMapper;
    @Autowired
    TbBizPlaceGoodsTypeMapper tbBizPlaceGoodsTypeMapper;
    @Autowired
    TbBizPlaceOrderMapper tbBizPlaceOrderMapper;
    @Autowired
    TbBizPlacePayItemMapper tbBizPlacePayItemMapper;
    @Autowired
    TbBizPlaceOrderItemMapper tbBizPlaceOrderItemMapper;
    @Autowired
    PlaceTicketService placeTicketService;
    @Autowired
    private PlaceMemberService placeMemberService;
    @Autowired
    private TbBizPlaceMemberCardMapper tbBizPlaceMemberCardMapper;
    @Autowired
    IBaseService iBaseService;
    @Autowired
    private TbBizPlaceMemberOpHistoryMapper tbBizPlaceMemberOpHistoryMapper;
    @Autowired
    BaseService baseService;
    @Autowired
    SmsService smsService;
    @Autowired
    VPlaceGoodsMapper vPlaceGoodsMapper;
    @Autowired
    TbBizPlaceMapper tbBizPlaceMapper;
    @Autowired
    PlaceBaseService placeBaseService;
    @Autowired
    PlaceOrderUtilService placeOrderUtilService;
    @Autowired
    com.quanyan.place.biz.SmsService placeSmsService;
    @Autowired
    TbBizPlaceGoodsInfoMapper tbBizPlaceGoodsInfoMapper;
    @Autowired
    TbBizPlaceGoodsInputInventoryMapper tbBizPlaceGoodsInputInventoryMapper;
    @Autowired
    TbBizPlaceGoodsInputInventoryDetailMapper tbBizPlaceGoodsInputInventoryDetailMapper;
    @Autowired
    AdminUserService adminUserService;
    @Autowired
    DictMapper dictMapper;
    @Autowired
    TbSupplierMapper tbSupplierMapper;
    @Autowired
    TbCityMapper tbCityMapper;
    @Autowired
    TbBizPlaceGoodsCheckRecordMapper tbBizPlaceGoodsCheckRecordMapper;
    @Autowired
    TbBizPlaceGoodsHistoryMapper tbBizPlaceGoodsHistoryMapper;
    @Autowired
    TbBizPlaceGoodsTypeCommonMapper tbBizPlaceGoodsTypeCommonMapper;
    @Autowired
    TbBizPlaceGoodsCommonMapper tbBizPlaceGoodsCommonMapper;
   
    /**
     * 商品列表
     *
     * @param reqPlaceGoodsVo
     * @return
     */

    @Override
    public PageObj<List<RespPlaceGoodsVo>> getPlaceGoodsList(ReqPlaceGoodsVo reqPlaceGoodsVo) {
 /*       Integer pageNum = 0;
        Integer pageSize = Constants.DEFAULT_PAGE_SIZE;
        List<RespPlaceGoodsVo> respList = new ArrayList<>();

        TbBizPlaceGoodsExample example = new TbBizPlaceGoodsExample();
        TbBizPlaceGoodsExample.Criteria criteria = example.createCriteria();
        pageNum = reqPlaceGoodsVo.getPageNum();
        pageSize = reqPlaceGoodsVo.getPageSize();

        criteria.andIsDeleteEqualTo(0);
        if (!StringUtils.isEmpty(reqPlaceGoodsVo.getName())) {
            criteria.andNameLike("%" + reqPlaceGoodsVo.getName().trim() + "%");
        }

        if (reqPlaceGoodsVo.getType() != null) {
            criteria.andTypeEqualTo(reqPlaceGoodsVo.getType());
        }
        if (reqPlaceGoodsVo.getFlag() == 1) {
            if (reqPlaceGoodsVo.getStatus() != null) {
                criteria.andStatusEqualTo(reqPlaceGoodsVo.getStatus());
            }
            example.setOrderByClause("id desc");
            if (reqPlaceGoodsVo.getInventory() != null) {
                if (reqPlaceGoodsVo.getInventory().equals(1)) {
                    example.setOrderByClause("inventory asc");
                } else {
                    example.setOrderByClause("inventory desc");
                }
            }

        }

        //商品售卖条件
        if (reqPlaceGoodsVo.getFlag() == 2) {
            criteria.andInventoryGreaterThan(0);
            criteria.andStatusEqualTo(1);
            example.setOrderByClause("id desc");
        }
        criteria.andPlaceIdEqualTo(reqPlaceGoodsVo.getPlaceId());
        int total = tbBizPlaceGoodsMapper.countByExample(example);
        example.setPage(new Page(pageNum * pageSize, pageSize, total));
        List<TbBizPlaceGoods> list = tbBizPlaceGoodsMapper.selectByExample(example);
        Map<String,Object> mapOneLevel=new HashMap<>();
        Map<Integer,Object> mapTwoLevel=new HashMap<>();
        List<Dict> listDict = this.getOneLevel(null);
          for (Dict vo:listDict){
              mapOneLevel.put(vo.getDataKey(),vo.getDataValue());
          }
        List<TbBizPlaceGoodsType> typeList = this.getGoodsTypeNameByTypeId(null,reqPlaceGoodsVo.getPlaceId());
           for (TbBizPlaceGoodsType type:typeList){
                mapTwoLevel.put(type.getId(),type.getName());
           }

        for (TbBizPlaceGoods vo : list) {
            RespPlaceGoodsVo resp = new RespPlaceGoodsVo();
            resp.setId(vo.getId());
            resp.setGoodsId(vo.getGoodsId());
            resp.setName(vo.getName());
            resp.setCostPrice(vo.getCostPrice());
            resp.setInventory(vo.getInventory());
            resp.setMemberPrice(vo.getMemberPrice());
            resp.setSalePrice(vo.getSalePrice());
            resp.setPlaceId(vo.getPlaceId());
            resp.setType(vo.getType());
            resp.setStatus(vo.getStatus());
            resp.setUpDownTime(vo.getUpDownTime());
            //TbBizPlaceGoodsType voType = this.getGoodsTypeNameByTypeId(vo.getType(), reqPlaceGoodsVo.getPlaceId());
            //通过商品找到所属商品类别
           reqPlaceGoodsVo.setGoodsId(vo.getGoodsId());
           TbBizPlaceGoodsInfo goodsInfo=this.getGoodsInfoByGoods(reqPlaceGoodsVo);
            if (goodsInfo!=null){
                resp.setGoodsStandard(goodsInfo.getGoodsStandard());
                resp.setOneLevel(mapOneLevel.get(goodsInfo.getOneLevelTypeId().toString()).toString());
                resp.setOneLevelId(goodsInfo.getOneLevelTypeId().toString());
                if (goodsInfo.getTwoLevelTypeId()!=null){
                    resp.setTwoLevel(mapTwoLevel.get(goodsInfo.getTwoLevelTypeId()).toString());
                    resp.setTwoLevelId(goodsInfo.getTwoLevelTypeId());
                }
            }

            if (PlaceConstants.PLACE_GOODS_STATUS_SALE.equals(vo.getStatus())) {
                resp.setStatusName("上架");
            }
            if (PlaceConstants.PLACE_GOODS_STATUS_UNSALE.equals(vo.getStatus())) {
                resp.setStatusName("下架");
            }
            respList.add(resp);
        }
        PageObj<List<RespPlaceGoodsVo>> result = PageObj.create(total, pageNum, pageSize, respList);
        return result;*/

        if (!StringUtils.isEmpty(reqPlaceGoodsVo.getName())) {
            reqPlaceGoodsVo.setName("%" + reqPlaceGoodsVo.getName().trim() + "%");
        } else {
            reqPlaceGoodsVo.setName(null);
        }


        Integer pageNum = reqPlaceGoodsVo.getPageNum();
        Integer pageSize = reqPlaceGoodsVo.getPageSize();
        if (reqPlaceGoodsVo.getPageNum() == null) {
            reqPlaceGoodsVo.setPageNum(0);
        }
        if (reqPlaceGoodsVo.getPageSize() == null) {
            reqPlaceGoodsVo.setPageSize(Constants.DEFAULT_PAGE_SIZE);
        }
        int total = vPlaceGoodsMapper.getPlaceGoodsListCount(reqPlaceGoodsVo);
        reqPlaceGoodsVo.setPage(new Page(pageNum * pageSize, pageSize, total));
        List<RespPlaceGoodsVo> list = vPlaceGoodsMapper.getPlaceGoodsList(reqPlaceGoodsVo);

        Map<String, Object> mapOneLevel = new HashMap<>();
        Map<Integer, Object> mapTwoLevel = new HashMap<>();
        List<Dict> listDict = this.getOneLevel(null);
        for (Dict vo : listDict) {
            mapOneLevel.put(vo.getDataKey(), vo.getDataValue());
        }
        List<TbBizPlaceGoodsType> typeList = this.getGoodsTypeNameByTypeId(null, reqPlaceGoodsVo.getPlaceId());
        for (TbBizPlaceGoodsType type : typeList) {
            mapTwoLevel.put(type.getId(), type.getName());
        }

        for (RespPlaceGoodsVo resp : list) {
            reqPlaceGoodsVo.setGoodsId(resp.getGoodsId());
            TbBizPlaceGoodsInfo goodsInfo = this.getGoodsInfoByGoods(reqPlaceGoodsVo);
            if (goodsInfo != null) {
                resp.setGoodsStandard(goodsInfo.getGoodsStandard());
                if (goodsInfo.getOneLevelTypeId() != null) {
                    resp.setOneLevel(mapOneLevel.get(goodsInfo.getOneLevelTypeId().toString()).toString());
                    resp.setOneLevelId(goodsInfo.getOneLevelTypeId().toString());
                }
                if (goodsInfo.getTwoLevelTypeId() != null) {
                    Object obj = mapTwoLevel.get(goodsInfo.getTwoLevelTypeId());
                    resp.setTwoLevel(obj != null ? obj.toString() : "");
                    resp.setTypeName(obj != null ? obj.toString() : "");
                    resp.setTwoLevelId(goodsInfo.getTwoLevelTypeId());
                } else {
                    if (resp.getType() != null) {
                        Object obj = mapTwoLevel.get(resp.getType());
                        resp.setTwoLevel(obj != null ? obj.toString() : "");
                        resp.setTwoLevelId(resp.getType());
                    }
                }
            } else {
                if (resp.getType() != null) {
                    Object obj = mapTwoLevel.get(resp.getType());
                    resp.setTwoLevel(obj != null ? obj.toString() : "");
                    resp.setTwoLevelId(resp.getType());
                }
            }

            if (PlaceConstants.PLACE_GOODS_STATUS_SALE.equals(resp.getStatus())) {
                resp.setStatusName("上架");
            }
            if (PlaceConstants.PLACE_GOODS_STATUS_UNSALE.equals(resp.getStatus())) {
                resp.setStatusName("下架");
            }
        }
        PageObj<List<RespPlaceGoodsVo>> result = PageObj.create(total, pageNum, pageSize, list);
        return result;
    }



    @Override
    public PageObj<List<RespPlaceGoodsVo>> getPlaceGoodsListNew(ReqPlaceGoodsVo reqPlaceGoodsVo) {
        if (!StringUtils.isEmpty(reqPlaceGoodsVo.getName())) {
            reqPlaceGoodsVo.setName("%" + reqPlaceGoodsVo.getName().trim() + "%");
        } else {
            reqPlaceGoodsVo.setName(null);
        }
        if (!StringUtils.isEmpty(reqPlaceGoodsVo.getGoodsCode())) {
            reqPlaceGoodsVo.setGoodsCode("%" + reqPlaceGoodsVo.getGoodsCode().trim() + "%");
        } else {
            reqPlaceGoodsVo.setGoodsCode(null);
        }
        if (!StringUtils.isEmpty(reqPlaceGoodsVo.getBarCode())) {
            reqPlaceGoodsVo.setBarCode("%" + reqPlaceGoodsVo.getBarCode().trim() + "%");
        } else {
            reqPlaceGoodsVo.setBarCode(null);
        }
        if (!StringUtils.isEmpty(reqPlaceGoodsVo.getTwoLevel())) {
            reqPlaceGoodsVo.setTwoLevel("%" + reqPlaceGoodsVo.getTwoLevel().trim() + "%");
        } else {
            reqPlaceGoodsVo.setTwoLevel(null);
        }

        Integer pageNum = reqPlaceGoodsVo.getPageNum();
        Integer pageSize = reqPlaceGoodsVo.getPageSize();
        if (reqPlaceGoodsVo.getPageNum() == null) {
            reqPlaceGoodsVo.setPageNum(0);
        }
        if (reqPlaceGoodsVo.getPageSize() == null) {
            reqPlaceGoodsVo.setPageSize(Constants.DEFAULT_PAGE_SIZE);
        }
        int total = vPlaceGoodsMapper.getPlaceGoodsListCountNew(reqPlaceGoodsVo);
        reqPlaceGoodsVo.setPage(new Page(pageNum * pageSize, pageSize, total));
        List<RespPlaceGoodsVo> list = vPlaceGoodsMapper.getPlaceGoodsListNew(reqPlaceGoodsVo);
        Map<String, Object> mapOneLevel = new HashMap<>();
        List<Dict> listDict = this.getOneLevel(null);
        for (Dict vo : listDict) {
            mapOneLevel.put(vo.getDataKey(), vo.getDataValue());
        }
        for (RespPlaceGoodsVo resp : list) {
            reqPlaceGoodsVo.setGoodsId(resp.getGoodsId());
            TbBizPlaceGoodsInfo goodsInfo = this.getGoodsInfoByGoods(reqPlaceGoodsVo);
            if (goodsInfo != null) {
                resp.setGoodsStandard(goodsInfo.getGoodsStandard());
                if (goodsInfo.getOneLevelTypeId() != null) {
                    resp.setOneLevel(mapOneLevel.get(goodsInfo.getOneLevelTypeId().toString()).toString());
                    resp.setOneLevelId(goodsInfo.getOneLevelTypeId().toString());
                }
            }
            if (PlaceConstants.PLACE_GOODS_STATUS_SALE.equals(resp.getStatus())) {
                resp.setStatusName("上架");
            }
            if (PlaceConstants.PLACE_GOODS_STATUS_UNSALE.equals(resp.getStatus())) {
                resp.setStatusName("下架");
            }
        }
        PageObj<List<RespPlaceGoodsVo>> result = PageObj.create(total, pageNum, pageSize, list);
        return result;
    }
    /**
     * 新增商品信息
     *
     * @param reqPlaceGoodsVo
     */
   /*@Override
    public APIResponse insertPlaceGoodsInfo(ReqPlaceGoodsVo reqPlaceGoodsVo) {

    if (reqPlaceGoodsVo.getOneLevelId()==null || reqPlaceGoodsVo.getTwoLevelId()==null){
       return APIResponse.returnFail("请先录入商品类型！");
    }
        //判断导入的商品跟以前录入商品的有没重复
        TbBizPlaceGoodsExample example = new TbBizPlaceGoodsExample();
        TbBizPlaceGoodsExample.Criteria criteria = example.createCriteria();
        criteria.andNameEqualTo(reqPlaceGoodsVo.getName().trim());
        criteria.andPlaceIdEqualTo(reqPlaceGoodsVo.getPlaceId());
        criteria.andIsDeleteEqualTo(0);
        List<TbBizPlaceGoods> list = tbBizPlaceGoodsMapper.selectByExample(example);
        if (list.size() > 0) {
            return APIResponse.returnFail("'" + list.get(0).getName() + "'" + " " + "商品名称已经存在:");
        }
        TbBizPlaceGoods goods = new TbBizPlaceGoods();
        goods.setGoodsId(UUIDUtils.getUUID());
        goods.setType(reqPlaceGoodsVo.getType());
        goods.setSalePrice(reqPlaceGoodsVo.getSalePrice());
        goods.setMemberPrice(reqPlaceGoodsVo.getMemberPrice());
        goods.setCostPrice(reqPlaceGoodsVo.getCostPrice());
        goods.setInventory(0);
        goods.setName(reqPlaceGoodsVo.getName());
        goods.setStatus(reqPlaceGoodsVo.getStatus());
        goods.setPlaceId(reqPlaceGoodsVo.getPlaceId());
        goods.setIsDelete(0);
        goods.setUpDownTime(new Date());
        tbBizPlaceGoodsMapper.insert(goods);
        return APIResponse.returnSuccess();
    }*/
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public APIResponse insertPlaceGoodsInfo(ReqPlaceGoodsVo reqPlaceGoodsVo) {
        /*if (reqPlaceGoodsVo.getOneLevelId()==null||reqPlaceGoodsVo.getTwoLevelId()==null){
            return APIResponse.returnFail("请先录入商品类型！");
        }*/
        if (StringUtils.isEmpty(reqPlaceGoodsVo.getBarCode())){
            return APIResponse.returnFail("商品条码不能为空");
        }
        if (StringUtils.isEmpty(reqPlaceGoodsVo.getName())){
            return APIResponse.returnFail("商品名称不能为空");
        }
        if (StringUtils.isEmpty(reqPlaceGoodsVo.getSalePrice())){
            return APIResponse.returnFail("商品售价不能为空");
        }
        if (StringUtils.isEmpty(reqPlaceGoodsVo.getMemberPrice())){
            return APIResponse.returnFail("商品会员价不能为空");
        }
        if (!StringUtils.isEmpty(reqPlaceGoodsVo.getBarCode())){
            TbBizPlaceGoodsInfo infoVo=this.checkBarCode(reqPlaceGoodsVo.getPlaceId(),reqPlaceGoodsVo.getBarCode(),null);
            if (infoVo!=null){
                return APIResponse.returnFail("该商品条码已存在！");
            }
        }
        //判断导入的商品跟以前录入商品的有没重复
        TbBizPlaceGoodsInfoExample example = new TbBizPlaceGoodsInfoExample();
        TbBizPlaceGoodsInfoExample.Criteria criteria = example.createCriteria();
        criteria.andGoodsNameEqualTo(reqPlaceGoodsVo.getName().trim());
        criteria.andPlaceIdEqualTo(reqPlaceGoodsVo.getPlaceId());
        criteria.andIsDeleteEqualTo(0);
        List<TbBizPlaceGoodsInfo> list = tbBizPlaceGoodsInfoMapper.selectByExample(example);
        if (list!=null&&list.size() > 0) {
            return APIResponse.returnFail("'" + list.get(0).getGoodsName() + "'" + " " + "商品名称已经存在:");
        }
        TbBizPlaceGoodsInfo info = new TbBizPlaceGoodsInfo();
        info.setGoodsId(UUIDUtils.getUUID());
        info.setOneLevelTypeId(reqPlaceGoodsVo.getOneLevelId());
        info.setTwoLevelTypeId(reqPlaceGoodsVo.getTwoLevelId());
        info.setBarCode(reqPlaceGoodsVo.getBarCode());
        info.setGoodsName(reqPlaceGoodsVo.getName());
        info.setGoodsStandard(reqPlaceGoodsVo.getGoodsStandard());
        info.setIsDelete(0);
        info.setPlaceId(reqPlaceGoodsVo.getPlaceId());
        info.setIsGive(reqPlaceGoodsVo.getIsGive() != null ? Integer.parseInt(reqPlaceGoodsVo.getIsGive()) : 0);
        info.setIsHotSale(reqPlaceGoodsVo.getIsHotSale() != null ? Integer.parseInt(reqPlaceGoodsVo.getIsHotSale()) : 0);
        tbBizPlaceGoodsInfoMapper.insert(info);

        TbBizPlaceGoods goods = new TbBizPlaceGoods();
        goods.setInventory(0);
        goods.setName(reqPlaceGoodsVo.getName());
        goods.setGoodsId(info.getGoodsId());
        goods.setPlaceId(info.getPlaceId());
        goods.setIsDelete(0);
        goods.setStatus(2);
        goods.setCostPrice(BigDecimal.ZERO);
        goods.setMemberPrice(reqPlaceGoodsVo.getMemberPrice());
        goods.setSalePrice(reqPlaceGoodsVo.getSalePrice());

        tbBizPlaceGoodsMapper.insert(goods);
        return APIResponse.returnSuccess("新增商品成功");
    }
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public APIResponse insertPlaceGoodsInfoNew(ReqPlaceGoodsVo reqPlaceGoodsVo) {
        if(checkGoodsInfo(reqPlaceGoodsVo)!=null){
            return checkGoodsInfo(reqPlaceGoodsVo);
        }else{
            TbBizPlaceGoodsInfo info = new TbBizPlaceGoodsInfo();
            info.setGoodsId(UUIDUtils.getUUID());
            info.setOneLevelTypeId(reqPlaceGoodsVo.getOneLevelId());
            info.setTwoLevelTypeId(reqPlaceGoodsVo.getTwoLevelId());
            info.setBarCode(reqPlaceGoodsVo.getBarCode());
            info.setGoodsName(reqPlaceGoodsVo.getName());
            info.setGoodsStandard(reqPlaceGoodsVo.getGoodsStandard());
            info.setIsDelete(0);
            info.setPlaceId(reqPlaceGoodsVo.getPlaceId());
            info.setIsGive(reqPlaceGoodsVo.getIsGive() != null ? Integer.parseInt(reqPlaceGoodsVo.getIsGive()) : 0);
            info.setIsHotSale(reqPlaceGoodsVo.getIsHotSale() != null ? Integer.parseInt(reqPlaceGoodsVo.getIsHotSale()) : 0);
            info.setGoodsCode(reqPlaceGoodsVo.getGoodsCode());
            info.setGoodsImgUrl(reqPlaceGoodsVo.getGoodsImgUrl());
            info.setGoodsUnit(reqPlaceGoodsVo.getGoodsUnit());
            info.setGoodsCommonId(reqPlaceGoodsVo.getGoodsCommonId());
            tbBizPlaceGoodsInfoMapper.insert(info);
            TbBizPlaceGoods goods = new TbBizPlaceGoods();
            goods.setInventory(0);
            goods.setName(reqPlaceGoodsVo.getName());
            goods.setGoodsId(info.getGoodsId());
            goods.setPlaceId(info.getPlaceId());
            goods.setIsDelete(0);
            goods.setStatus(2);
            goods.setCostPrice(BigDecimal.ZERO);
            goods.setMemberPrice(reqPlaceGoodsVo.getMemberPrice());
            goods.setSalePrice(reqPlaceGoodsVo.getSalePrice());
            tbBizPlaceGoodsMapper.insert(goods);
            return APIResponse.returnSuccess("新增商品成功");
        }
    }

    /**
     * 更新商品信息
     *
     * @param reqPlaceGoodsVo
     */
    @Override
    public APIResponse updatePlaceGoodsInfo(ReqPlaceGoodsVo reqPlaceGoodsVo) {
        /*TbBizPlaceGoodsInfo InfoVo=this.getGoodsInfoByGoodsId(reqPlaceGoodsVo.getGoodsId(),reqPlaceGoodsVo.getPlaceId());
        if (InfoVo!=null){
          return  APIResponse.returnFail("该商品名称已存在");
        }*/
        TbBizPlaceGoodsInfo info = this.checkGoodsName(null, reqPlaceGoodsVo.getName(), reqPlaceGoodsVo.getGoodsId());
        if (info == null) {
            TbBizPlaceGoodsInfo val = this.checkGoodsName(reqPlaceGoodsVo.getPlaceId(), reqPlaceGoodsVo.getName(), null);
            if (val != null) {
                return APIResponse.returnFail("该商品名称已存在");
            }
        }

        TbBizPlaceGoodsInfo vos = this.checkBarCode(null, reqPlaceGoodsVo.getBarCode(), reqPlaceGoodsVo.getGoodsId());
        if (vos == null) {
            TbBizPlaceGoodsInfo io = this.checkBarCode(reqPlaceGoodsVo.getPlaceId(), reqPlaceGoodsVo.getBarCode(), null);
            if (io != null) {
                return APIResponse.returnFail("该商品条码已存在");
            }
        }
        if (StringUtils.isEmpty(reqPlaceGoodsVo.getSalePrice())) {
            return APIResponse.returnFail("商品售价不能为空");
        }
        if (StringUtils.isEmpty(reqPlaceGoodsVo.getMemberPrice())) {
            return APIResponse.returnFail("商品会员价不能为空");
        }
        TbBizPlaceGoods goods = new TbBizPlaceGoods();
        goods.setId(reqPlaceGoodsVo.getId());
        goods.setName(reqPlaceGoodsVo.getName());
        goods.setInventory(reqPlaceGoodsVo.getInventory());
        goods.setStatus(reqPlaceGoodsVo.getStatus());
        goods.setMemberPrice(reqPlaceGoodsVo.getMemberPrice());
        goods.setCostPrice(reqPlaceGoodsVo.getCostPrice());
        goods.setType(reqPlaceGoodsVo.getType());
        goods.setSalePrice(reqPlaceGoodsVo.getSalePrice());
        TbBizPlaceGoods vo = this.getGoodsInfoByid(reqPlaceGoodsVo);
        if (vo != null) {
            if (!vo.getStatus().equals(reqPlaceGoodsVo.getStatus())) {
                goods.setUpDownTime(new Date());
            }
        }

        //更新商品类别，名称
        updatePlaceGoodsData(reqPlaceGoodsVo);
        tbBizPlaceGoodsMapper.updateByPrimaryKeySelective(goods);
        return APIResponse.returnSuccess("更新商品成功");


    }

    @Override
    public APIResponse updatePlaceGoodsInfoNew(ReqPlaceGoodsVo reqPlaceGoodsVo) {
        if (StringUtils.isEmpty(reqPlaceGoodsVo.getSalePrice())) {
            return APIResponse.returnFail("商品售价不能为空");
        }
        if (StringUtils.isEmpty(reqPlaceGoodsVo.getMemberPrice())) {
            return APIResponse.returnFail("商品会员价不能为空");
        }
        TbBizPlaceGoods goods = new TbBizPlaceGoods();
        goods.setId(reqPlaceGoodsVo.getId());
        goods.setName(reqPlaceGoodsVo.getName());
        goods.setInventory(reqPlaceGoodsVo.getInventory());
        goods.setMemberPrice(reqPlaceGoodsVo.getMemberPrice());
        goods.setCostPrice(reqPlaceGoodsVo.getCostPrice());
        goods.setType(reqPlaceGoodsVo.getType());
        goods.setSalePrice(reqPlaceGoodsVo.getSalePrice());
        //更新商品类别，名称
        updatePlaceGoodsDataNew(reqPlaceGoodsVo);
        tbBizPlaceGoodsMapper.updateByPrimaryKeySelective(goods);
        return APIResponse.returnSuccess("更新商品成功");
    }

    public TbBizPlaceGoodsInfo checkBarCode(Integer placeId, String barCode, String goodsId) {
        TbBizPlaceGoodsInfoExample example = new TbBizPlaceGoodsInfoExample();
        TbBizPlaceGoodsInfoExample.Criteria criteria = example.createCriteria();
        if (placeId != null) {
            criteria.andPlaceIdEqualTo(placeId);
        }
        if (barCode != null) {
            criteria.andBarCodeEqualTo(barCode);
        }
        if (goodsId != null) {
            criteria.andGoodsIdEqualTo(goodsId);
        }
        criteria.andIsDeleteEqualTo(0);
        List<TbBizPlaceGoodsInfo> list = tbBizPlaceGoodsInfoMapper.selectByExample(example);
        if (list != null && list.size() > 0) {
            return list.get(0);
        } else {
            return null;
        }
    }

    public TbBizPlaceGoodsInfo checkGoodsName(Integer placeId, String goodsName, String goodsId) {
        TbBizPlaceGoodsInfoExample example = new TbBizPlaceGoodsInfoExample();
        TbBizPlaceGoodsInfoExample.Criteria criteria = example.createCriteria();
        if (placeId != null) {
            criteria.andPlaceIdEqualTo(placeId);
        }
        if (goodsName != null) {
            criteria.andGoodsNameEqualTo(goodsName);
        }
        if (goodsId != null) {
            criteria.andGoodsIdEqualTo(goodsId);
        }
        criteria.andIsDeleteEqualTo(0);
        List<TbBizPlaceGoodsInfo> list = tbBizPlaceGoodsInfoMapper.selectByExample(example);
        if (list != null && list.size() > 0) {
            return list.get(0);
        } else {
            return null;
        }
    }


    public TbBizPlaceGoodsType checkTypeName(Integer placeId,String typeName,Integer typeId){
        TbBizPlaceGoodsTypeExample example = new TbBizPlaceGoodsTypeExample();
        TbBizPlaceGoodsTypeExample.Criteria criteria = example.createCriteria();
        if (placeId!=null){
            criteria.andPlaceIdEqualTo(placeId);
        }
        if (typeName!=null){
            criteria.andNameEqualTo(typeName);
        }
        if (typeId!=null){
            criteria.andIdEqualTo(typeId);
        }
        criteria.andIsDeleteEqualTo(0);
        List<TbBizPlaceGoodsType> list = tbBizPlaceGoodsTypeMapper.selectByExample(example);
        if (list!=null&&list.size()>0){
            return  list.get(0);
        }else{
            return null;
        }
    }

    /**
     * 更新商品信息
     *
     * @param reqPlaceGoodsVo
     */
    public void updatePlaceGoodsData(ReqPlaceGoodsVo reqPlaceGoodsVo) {
        TbBizPlaceGoodsInfoExample example = new TbBizPlaceGoodsInfoExample();
        TbBizPlaceGoodsInfoExample.Criteria criteria = example.createCriteria();
        criteria.andGoodsIdEqualTo(reqPlaceGoodsVo.getGoodsId());
        criteria.andPlaceIdEqualTo((reqPlaceGoodsVo.getPlaceId()));

        TbBizPlaceGoodsInfo info = new TbBizPlaceGoodsInfo();
        info.setGoodsName(reqPlaceGoodsVo.getName());
        info.setOneLevelTypeId(reqPlaceGoodsVo.getOneLevelId());
        info.setTwoLevelTypeId(reqPlaceGoodsVo.getTwoLevelId());
        info.setIsGive(reqPlaceGoodsVo.getIsGive() != null ? Integer.parseInt(reqPlaceGoodsVo.getIsGive()) : 0);
        info.setIsHotSale(reqPlaceGoodsVo.getIsHotSale() != null ? Integer.parseInt(reqPlaceGoodsVo.getIsHotSale()) : 0);
        info.setBarCode(reqPlaceGoodsVo.getBarCode());
        info.setUpdateTime(new Date());
        /*if (reqPlaceGoodsVo.getTwoLevelId()==null){
            info.setTwoLevelTypeId(-1);
        }*/
        info.setGoodsStandard(reqPlaceGoodsVo.getGoodsStandard());
        tbBizPlaceGoodsInfoMapper.updateByExampleSelective(info, example);
    }

    public void updatePlaceGoodsDataNew(ReqPlaceGoodsVo reqPlaceGoodsVo) {
        TbBizPlaceGoodsInfoExample example = new TbBizPlaceGoodsInfoExample();
        TbBizPlaceGoodsInfoExample.Criteria criteria = example.createCriteria();
        criteria.andGoodsIdEqualTo(reqPlaceGoodsVo.getGoodsId());
        criteria.andPlaceIdEqualTo((reqPlaceGoodsVo.getPlaceId()));

        TbBizPlaceGoodsInfo info = new TbBizPlaceGoodsInfo();
        info.setGoodsName(reqPlaceGoodsVo.getName());
        info.setOneLevelTypeId(reqPlaceGoodsVo.getOneLevelId());
        info.setTwoLevelTypeId(reqPlaceGoodsVo.getTwoLevelId());
        info.setIsGive(reqPlaceGoodsVo.getIsGive() != null ? Integer.parseInt(reqPlaceGoodsVo.getIsGive()) : 0);
        info.setIsHotSale(reqPlaceGoodsVo.getIsHotSale() != null ? Integer.parseInt(reqPlaceGoodsVo.getIsHotSale()) : 0);
        info.setBarCode(reqPlaceGoodsVo.getBarCode());
        info.setGoodsCode(reqPlaceGoodsVo.getGoodsCode());
        info.setGoodsUnit(reqPlaceGoodsVo.getGoodsUnit());
        info.setGoodsImgUrl(reqPlaceGoodsVo.getGoodsImgUrl());
        info.setUpdateTime(new Date());
        info.setGoodsStandard(reqPlaceGoodsVo.getGoodsStandard());
        tbBizPlaceGoodsInfoMapper.updateByExampleSelective(info, example);
    }

    /**
     * 删除商品
     *
     * @param reqPlaceGoodsVo
     */
    @Override
    public void deletePlaceGoodsInfo(ReqPlaceGoodsVo reqPlaceGoodsVo) {
        TbBizPlaceGoods goods = new TbBizPlaceGoods();
        goods.setId(reqPlaceGoodsVo.getId());
        goods.setIsDelete(1);
        tbBizPlaceGoodsMapper.updateByPrimaryKeySelective(goods);
    }

    /**
     * 导出商品列表
     *
     * @param reqPlaceGoodsVo
     * @return
     */
    @Override
    public List<RespPlaceGoodsVo> exportPlaceGoodsInfo(ReqPlaceGoodsVo reqPlaceGoodsVo) {

        List<RespPlaceGoodsVo> respList = new ArrayList<>();
        TbBizPlaceGoodsExample goodsExample = new TbBizPlaceGoodsExample();
        TbBizPlaceGoodsExample.Criteria criteria = goodsExample.createCriteria();
        criteria.andPlaceIdEqualTo(reqPlaceGoodsVo.getPlaceId());
        criteria.andIsDeleteEqualTo(0);
        goodsExample.setOrderByClause("id desc");
        if (!StringUtils.isEmpty(reqPlaceGoodsVo.getName())) {
            criteria.andNameLike("%" + reqPlaceGoodsVo.getName() + "%");
        }
        if (reqPlaceGoodsVo.getStatus() != null) {
            criteria.andStatusEqualTo(reqPlaceGoodsVo.getStatus());
        }
        if (reqPlaceGoodsVo.getType() != null) {
            criteria.andTypeEqualTo(reqPlaceGoodsVo.getType());
        }
        if (reqPlaceGoodsVo.getInventory() != null) {
            if (reqPlaceGoodsVo.getInventory().equals(1)) {
                goodsExample.setOrderByClause("inventory asc");
            } else {
                goodsExample.setOrderByClause("inventory desc");
            }
        }
        List<TbBizPlaceGoods> list = tbBizPlaceGoodsMapper.selectByExample(goodsExample);
        Map<String, Object> mapOneLevel = this.getMapOneLevel(reqPlaceGoodsVo);
        Map<Integer, Object> mapTwoLevel = this.getMapTwoLevel(reqPlaceGoodsVo);
        for (TbBizPlaceGoods vo : list) {

            RespPlaceGoodsVo resp = new RespPlaceGoodsVo();
            resp.setId(vo.getId());
            resp.setName(vo.getName());
            resp.setCostPrice(vo.getCostPrice());
            resp.setInventory(vo.getInventory());
            resp.setMemberPrice(vo.getMemberPrice());
            resp.setSalePrice(vo.getSalePrice());
            //通过商品找到所属商品类别
            reqPlaceGoodsVo.setGoodsId(vo.getGoodsId());
            TbBizPlaceGoodsInfo goodsInfo = this.getGoodsInfoByGoods(reqPlaceGoodsVo);
            if (goodsInfo != null) {
                if (goodsInfo.getOneLevelTypeId() != null) {
                    resp.setOneLevel(mapOneLevel.get(goodsInfo.getOneLevelTypeId().toString()).toString());
                    resp.setOneLevelId(goodsInfo.getOneLevelTypeId().toString());
                } else {
                    resp.setOneLevel("");
                }
                if (goodsInfo.getTwoLevelTypeId() != null) {
                    resp.setTwoLevel(mapTwoLevel.get(goodsInfo.getTwoLevelTypeId()).toString());
                    resp.setTwoLevelId(goodsInfo.getTwoLevelTypeId());
                } else {
                    resp.setTwoLevel("");
                }
            }
            if (PlaceConstants.PLACE_GOODS_STATUS_SALE.equals(vo.getStatus())) {
                resp.setStatusName("上架");
            }
            if (PlaceConstants.PLACE_GOODS_STATUS_UNSALE.equals(vo.getStatus())) {
                resp.setStatusName("下架");
            }
            respList.add(resp);
        }
        return respList;
    }

    @Override
    public List<RespPlaceGoodsVo> exportPlaceGoodsInfoNew(ReqPlaceGoodsVo reqPlaceGoodsVo) {
        List<RespPlaceGoodsVo> respList = new ArrayList<>();
        TbBizPlaceGoodsExample goodsExample = new TbBizPlaceGoodsExample();
        TbBizPlaceGoodsExample.Criteria criteria = goodsExample.createCriteria();
        criteria.andPlaceIdEqualTo(reqPlaceGoodsVo.getPlaceId());
        criteria.andIsDeleteEqualTo(0);
        goodsExample.setOrderByClause("update_time desc");
        if (!StringUtils.isEmpty(reqPlaceGoodsVo.getName())) {
            criteria.andNameLike("%" + reqPlaceGoodsVo.getName() + "%");
        }
        if (reqPlaceGoodsVo.getStatus() != null) {
            criteria.andStatusEqualTo(reqPlaceGoodsVo.getStatus());
        }
        if (reqPlaceGoodsVo.getType() != null) {
            criteria.andTypeEqualTo(reqPlaceGoodsVo.getType());
        }
        if (reqPlaceGoodsVo.getInventory() != null) {
            if (reqPlaceGoodsVo.getInventory().equals(1)) {
                goodsExample.setOrderByClause("inventory asc");
            } else {
                goodsExample.setOrderByClause("inventory desc");
            }
        }
        if (reqPlaceGoodsVo.getIdFlag() != null) {
            if (reqPlaceGoodsVo.getInventory().equals(1)) {
                goodsExample.setOrderByClause("idFlag asc");
            } else {
                goodsExample.setOrderByClause("idFlag desc");
            }
        }
        List<TbBizPlaceGoods> list = tbBizPlaceGoodsMapper.selectByExample(goodsExample);
        Map<String, Object> mapOneLevel = this.getMapOneLevel(reqPlaceGoodsVo);
        Map<Integer, Object> mapTwoLevel = this.getMapTwoLevel(reqPlaceGoodsVo);
        for (TbBizPlaceGoods vo : list) {

            RespPlaceGoodsVo resp = new RespPlaceGoodsVo();
            resp.setId(vo.getId());
            resp.setName(vo.getName());
            resp.setCostPrice(vo.getCostPrice());
            resp.setInventory(vo.getInventory());
            resp.setMemberPrice(vo.getMemberPrice());
            resp.setSalePrice(vo.getSalePrice());
            //通过商品找到所属商品类别
            reqPlaceGoodsVo.setGoodsId(vo.getGoodsId());
            TbBizPlaceGoodsInfo goodsInfo = this.getGoodsInfoByGoods(reqPlaceGoodsVo);
            if (goodsInfo != null) {
                if (goodsInfo.getOneLevelTypeId() != null) {
                    resp.setOneLevel(mapOneLevel.get(goodsInfo.getOneLevelTypeId().toString()).toString());
                    resp.setOneLevelId(goodsInfo.getOneLevelTypeId().toString());
                } else {
                    resp.setOneLevel("");
                }
                if (goodsInfo.getTwoLevelTypeId() != null) {
                    resp.setTwoLevel(mapTwoLevel.get(goodsInfo.getTwoLevelTypeId()).toString());
                    resp.setTwoLevelId(goodsInfo.getTwoLevelTypeId());
                } else {
                    resp.setTwoLevel("");
                }
            }
            resp.setGoodsImgUrl(goodsInfo.getGoodsImgUrl());
            resp.setGoodsCode(goodsInfo.getGoodsCode());
            resp.setGoodsUnit(goodsInfo.getGoodsUnit());
            resp.setBarCode(goodsInfo.getBarCode());
            resp.setIsHotSale(goodsInfo.getIsHotSale());
            resp.setIsGive(goodsInfo.getIsGive());
            if (PlaceConstants.PLACE_GOODS_STATUS_SALE.equals(vo.getStatus())) {
                resp.setStatusName("上架");
            }
            if (PlaceConstants.PLACE_GOODS_STATUS_UNSALE.equals(vo.getStatus())) {
                resp.setStatusName("下架");
            }
            respList.add(resp);
        }
        return respList;
    }

    /**
     * 获得一级商品类别
     *
     * @param reqPlaceGoodsVo
     * @return
     */
    public Map<String, Object> getMapOneLevel(ReqPlaceGoodsVo reqPlaceGoodsVo) {
        Map<String, Object> mapOneLevel = new HashMap<>();
        List<Dict> listDict = this.getOneLevel(null);
        for (Dict vo : listDict) {
            mapOneLevel.put(vo.getDataKey(), vo.getDataValue());
        }
        return mapOneLevel;
    }

    /**
     * 获得一级商品类别key
     *
     * @param
     * @return
     */
    public Map<String, Integer> getMapOneLevelKeyByValue() {
        Map<String, Integer> mapOneLevel = new HashMap<>();
        List<Dict> listDict = this.getOneLevel(null);
        for (Dict vo : listDict) {
            mapOneLevel.put(vo.getDataValue(), Integer.parseInt(vo.getDataKey()));
        }
        return mapOneLevel;
    }

    /**
     * 获得二级商品类别key
     *
     * @param
     * @return
     */
    public Map<String, Integer> getMapTwoLevelKeyByValue(Integer placeId) {
        Map<String, Integer> mapTwoLevel = new HashMap<>();
        List<TbBizPlaceGoodsType> typeList = this.getGoodsTypeNameByTypeId(null, placeId);
        for (TbBizPlaceGoodsType vo : typeList) {
            mapTwoLevel.put(vo.getName(), vo.getId());
        }
        return mapTwoLevel;
    }

    /**
     * 获得二级商品类别
     *
     * @param reqPlaceGoodsVo
     * @return
     */
    public Map<Integer, Object> getMapTwoLevel(ReqPlaceGoodsVo reqPlaceGoodsVo) {
        Map<Integer, Object> mapTwoLevel = new HashMap<>();
        List<TbBizPlaceGoodsType> typeList = this.getGoodsTypeNameByTypeId(null, reqPlaceGoodsVo.getPlaceId());
        for (TbBizPlaceGoodsType type : typeList) {
            mapTwoLevel.put(type.getId(), type.getName());
        }
        return mapTwoLevel;
    }


    /**
     * 新增导入商品信息
     *
     * @param reqPlaceGoodsVo
     */
    @Override
    public APIResponse importPlaceGoodsInfo(ReqPlaceGoodsVo reqPlaceGoodsVo) {

        List<ReqPlaceGoodsVo> reqList = reqPlaceGoodsVo.getGoodsList();
        Map<Integer, Integer> mapLevel = new HashMap<>();
        Map<String, Integer> mapOneLevel = this.getMapOneLevelKeyByValue();
        Map<String, Integer> mapTwoLevel = this.getMapTwoLevelKeyByValue(reqPlaceGoodsVo.getPlaceId());

        ReqPlaceGoodsTypeVo typeVo = new ReqPlaceGoodsTypeVo();
        typeVo.setPlaceId(reqPlaceGoodsVo.getPlaceId());
        List<TbBizPlaceGoodsType> listType = this.getPlaceGoodsTypeData(typeVo);
        for (TbBizPlaceGoodsType type : listType) {
            mapLevel.put(type.getId(), type.getLevel());//存放场馆相对应的一级二级类别，key：二级，value：一级
        }
        //check商品一级二级类别是否匹配
        for (ReqPlaceGoodsVo voVal : reqList) {
            Integer oneLevelId = mapOneLevel.get(voVal.getOneLevel());
            Integer twoLevelId = mapTwoLevel.get(voVal.getTwoLevel());
            Integer oneId = mapLevel.get(twoLevelId);
            if (!oneLevelId.equals(oneId)) {
                return APIResponse.returnFail("商品一级二级类别不匹配，请检查！");
            }
        }
        for (ReqPlaceGoodsVo vo : reqList) {
            if (!(vo.getSalePrice() != null && vo.getMemberPrice() != null && vo.getOneLevel() != null && vo.getTwoLevel() != null && vo.getStatusName() != null && vo.getName() != null && vo.getGoodsStandard() != null)) {
                return APIResponse.returnFail("导入的数据存在空值！请检查！");
            }
         /*   if (vo.getTypeName().replaceAll("[^%&',;=?$\\x22]+", "").length() != 0) {
                return APIResponse.returnFail("导入失败！，请检查导入内容格式");
            }*/
            if (vo.getOneLevel().replaceAll("[^%&',;=?$\\x22]+", "").length() != 0) {
                return APIResponse.returnFail("导入失败！，请检查导入内容格式");
            }
            if (vo.getTwoLevel().replaceAll("[^%&',;=?$\\x22]+", "").length() != 0) {
                return APIResponse.returnFail("导入失败！，请检查导入内容格式");
            }

            if (vo.getStatusName().replaceAll("[^%&',;=?$\\x22]+", "").length() != 0) {
                return APIResponse.returnFail("导入失败！，请检查导入内容格式");
            }

            if (vo.getName().replaceAll("[^%&',;=?$\\x22]+", "").length() != 0) {
                return APIResponse.returnFail("导入失败！，请检查导入内容格式");
            }
            if (vo.getGoodsStandard().replaceAll("[^%&',;=?$\\x22]+", "").length() != 0) {
                return APIResponse.returnFail("导入失败！，请检查导入内容格式");
            }
            //校验存不存在导入的商品类别
            /* TbBizPlaceGoodsType type = this.getGoodsTypeTypeIdByName(vo.getTypeName().trim(), reqPlaceGoodsVo.getPlaceId());
             if(type==null){
                 return APIResponse.returnFail("系统中不存在"+"'"+vo.getTypeName()+"'"+"商品类别");
             }*/
            if (!mapOneLevel.containsKey(vo.getOneLevel())) {
                return APIResponse.returnFail("系统中不存在" + "'" + vo.getOneLevel() + "'" + "商品类别");
            }
            if (!mapTwoLevel.containsKey(vo.getTwoLevel())) {
                return APIResponse.returnFail("系统中不存在" + "'" + vo.getTwoLevel() + "'" + "商品类别");
            }
            if (!(vo.getStatusName().trim().equals("上架") || vo.getStatusName().trim().equals("下架"))) {
                return APIResponse.returnFail("商品状态只能是上架或下架");
            }

            String temp = "";
            //判断导入文件里面商品名称是否有重复
            for (int i = 0; i < reqList.size() - 1; i++) {
                temp = reqList.get(i).getName();
                for (int j = i + 1; j < reqList.size(); j++) {
                    if (temp.equals(reqList.get(j).getName())) {
                        return APIResponse.returnFail("第" + (i + 1) + "个跟第" + (j + 1) + "个商品名称重复");
                    }
                }
            }

            //判断导入的商品跟以前录入商品的有没重复
            TbBizPlaceGoodsExample example = new TbBizPlaceGoodsExample();
            TbBizPlaceGoodsExample.Criteria criteria = example.createCriteria();
            criteria.andNameEqualTo(vo.getName().trim());
            criteria.andPlaceIdEqualTo(reqPlaceGoodsVo.getPlaceId());
            criteria.andIsDeleteEqualTo(0);
            List<TbBizPlaceGoods> list = tbBizPlaceGoodsMapper.selectByExample(example);
            if (list.size() > 0) {
                return APIResponse.returnFail("'" + list.get(0).getName() + "'" + " " + "商品名称已经存在:");
            }
        }
        for (ReqPlaceGoodsVo reqVo : reqList) {
          /*  TbBizPlaceGoods goods = new TbBizPlaceGoods();
            goods.setGoodsId(UUIDUtils.getUUID());
            goods.setSalePrice(reqVo.getSalePrice());
            goods.setMemberPrice(reqVo.getMemberPrice());
            goods.setCostPrice(reqVo.getCostPrice());
            goods.setInventory(reqVo.getInventory());
            goods.setName(reqVo.getName().trim());
            goods.setPlaceId(reqPlaceGoodsVo.getPlaceId());
            goods.setIsDelete(0);
            goods.setUpDownTime(new Date());
            if (reqVo.getStatusName().trim().equals("上架")) {
                goods.setStatus(PlaceConstants.PLACE_GOODS_STATUS_SALE);
            } else if (reqVo.getStatusName().trim().equals("下架")) {
                goods.setStatus(PlaceConstants.PLACE_GOODS_STATUS_UNSALE);
            }
            //获取商品类别ID
           *//* TbBizPlaceGoodsType type = this.getGoodsTypeTypeIdByName(reqVo.getTypeName().trim(), reqPlaceGoodsVo.getPlaceId());
            if (type != null) {
                goods.setType(type.getId());
            }*//*
            tbBizPlaceGoodsMapper.insert(goods);*/
            TbBizPlaceGoodsInfo info = new TbBizPlaceGoodsInfo();
            info.setGoodsId(UUIDUtils.getUUID());
            info.setOneLevelTypeId(mapOneLevel.get(reqVo.getOneLevel().toString()));
            info.setTwoLevelTypeId(mapTwoLevel.get(reqVo.getTwoLevel()));
            info.setGoodsName(reqVo.getName());
            info.setGoodsStandard(reqVo.getGoodsStandard());
            info.setIsDelete(0);
            info.setPlaceId(reqPlaceGoodsVo.getPlaceId());
            info.setGoodsStandard(reqVo.getGoodsStandard());
            tbBizPlaceGoodsInfoMapper.insert(info);

            TbBizPlaceGoods goods = new TbBizPlaceGoods();
            goods.setInventory(0);
            goods.setName(reqVo.getName());
            goods.setGoodsId(info.getGoodsId());
            goods.setPlaceId(reqPlaceGoodsVo.getPlaceId());
            goods.setIsDelete(0);
            goods.setUpDownTime(new Date());
            if (reqVo.getStatusName().trim().equals("上架")) {
                goods.setStatus(PlaceConstants.PLACE_GOODS_STATUS_SALE);

            } else if (reqVo.getStatusName().trim().equals("下架")) {
                goods.setStatus(PlaceConstants.PLACE_GOODS_STATUS_UNSALE);
            }
            goods.setCostPrice(BigDecimal.ZERO);
            goods.setMemberPrice(reqVo.getMemberPrice());
            goods.setSalePrice(reqVo.getSalePrice());
            tbBizPlaceGoodsMapper.insert(goods);
        }

        return APIResponse.returnSuccess();
    }


    /**
     * 新增商品类型
     *
     * @param reqPlaceGoodsTypeVo
     */
    @Override
    public APIResponse insertPlaceGoodsTypeData(ReqPlaceGoodsTypeVo reqPlaceGoodsTypeVo) {
        //当父类做成下拉时用此代码
        if (reqPlaceGoodsTypeVo.getOneLevelId() == null) {
            return APIResponse.returnFail("一级类别不能为空！");
        }
        TbBizPlaceGoodsTypeExample typeExample = new TbBizPlaceGoodsTypeExample();
        TbBizPlaceGoodsTypeExample.Criteria criteria = typeExample.createCriteria();
        TbBizPlaceGoodsTypeExample.Criteria criteria2 = typeExample.createCriteria();
        criteria.andPlaceIdEqualTo(reqPlaceGoodsTypeVo.getPlaceId());
        if (reqPlaceGoodsTypeVo.getOneLevelId() != null) {
            if (StringUtils.isEmpty(reqPlaceGoodsTypeVo.getTwoLevel())) {
                return APIResponse.returnFail("二级类别不能为空");
            } else {
                criteria.andNameEqualTo(reqPlaceGoodsTypeVo.getTwoLevel().trim());
                List<TbBizPlaceGoodsType> list = tbBizPlaceGoodsTypeMapper.selectByExample(typeExample);
                if (list != null && list.size() > 0) {
                    return APIResponse.returnFail("该商品类型名称已存在!");
                }
                TbBizPlaceGoodsType type = new TbBizPlaceGoodsType();
                type.setName(reqPlaceGoodsTypeVo.getTwoLevel().trim());
                type.setLevel(reqPlaceGoodsTypeVo.getOneLevelId());
                type.setPlaceId(reqPlaceGoodsTypeVo.getPlaceId());
                type.setIsDelete(Constants.ZERO);
                tbBizPlaceGoodsTypeMapper.insert(type);
                return APIResponse.returnSuccess();
            }
        }
      /*else{
            TbBizPlaceGoodsType typeVo=new TbBizPlaceGoodsType();
            typeVo.setName(reqPlaceGoodsTypeVo.getOneLevel().trim());
            typeVo.setPlaceId(reqPlaceGoodsTypeVo.getPlaceId());
            tbBizPlaceGoodsTypeMapper.insertSelective(typeVo);
            if (!StringUtils.isEmpty(reqPlaceGoodsTypeVo.getTwoLevel())){
                TbBizPlaceGoodsType typeValue=new TbBizPlaceGoodsType();
                typeValue.setName(reqPlaceGoodsTypeVo.getTwoLevel().trim());
                typeValue.setLevel(typeVo.getId());
                typeVo.setPlaceId(reqPlaceGoodsTypeVo.getPlaceId());
                tbBizPlaceGoodsTypeMapper.insertSelective(typeValue);
            }
        }*/
        /*当父类做成手动输入的时候用此代码
       String oneLevel=reqPlaceGoodsTypeVo.getOneLevel().trim();
       String twoLevel=reqPlaceGoodsTypeVo.getTwoLevel().trim();
        if (StringUtils.isEmpty(oneLevel)){
            return APIResponse.returnFail("一级类别不能为空！");
        }
        TbBizPlaceGoodsTypeExample typeExampleOne =new TbBizPlaceGoodsTypeExample();
        TbBizPlaceGoodsTypeExample.Criteria criteriaOne=typeExampleOne.createCriteria();
        criteriaOne.andNameEqualTo(oneLevel);
        List<TbBizPlaceGoodsType> list=tbBizPlaceGoodsTypeMapper.selectByExample(typeExampleOne);
        if (list==null||list.size()<=0){//当一级商品类别是新增加时
            TbBizPlaceGoodsType type=new TbBizPlaceGoodsType();
            type.setName(oneLevel);
            type.setPlaceId(reqPlaceGoodsTypeVo.getPlaceId());
            tbBizPlaceGoodsTypeMapper.insert(type);
            if (!StringUtils.isEmpty(twoLevel)){
                TbBizPlaceGoodsTypeExample typeExample =new TbBizPlaceGoodsTypeExample();
                TbBizPlaceGoodsTypeExample.Criteria criteria=typeExample.createCriteria();
                criteria.andNameEqualTo(twoLevel);
                List<TbBizPlaceGoodsType> listVo=tbBizPlaceGoodsTypeMapper.selectByExample(typeExample);
                if (listVo!=null&&listVo.size()>0){
                    return APIResponse.returnFail("该商品类型名称已存在!");
                }
                TbBizPlaceGoodsType typeVo=new TbBizPlaceGoodsType();
                type.setName(twoLevel);
                type.setPlaceId(reqPlaceGoodsTypeVo.getPlaceId());
                type.setLevel(type.getId());
                tbBizPlaceGoodsTypeMapper.insert(type);
            }
        }else{//当一级类别不是新增加时
            TbBizPlaceGoodsType typeVo=new TbBizPlaceGoodsType();
            typeVo.setName(twoLevel);
            typeVo.setPlaceId(reqPlaceGoodsTypeVo.getPlaceId());
            typeVo.setLevel(list.get(0).getId());
            tbBizPlaceGoodsTypeMapper.insert(typeVo);
        }
         */
        return APIResponse.returnSuccess();
    }

    /**
     * 获取商品类型
     *
     * @param reqPlaceGoodsTypeVo
     */
    @Override
    public List<TbBizPlaceGoodsType> getPlaceGoodsTypeData(ReqPlaceGoodsTypeVo reqPlaceGoodsTypeVo) {
        TbBizPlaceGoodsTypeExample typeExample = new TbBizPlaceGoodsTypeExample();
        TbBizPlaceGoodsTypeExample.Criteria criteria = typeExample.createCriteria();
        criteria.andPlaceIdEqualTo(reqPlaceGoodsTypeVo.getPlaceId());
        criteria.andIsDeleteEqualTo(Constants.ZERO);
        List<TbBizPlaceGoodsType> list = tbBizPlaceGoodsTypeMapper.selectByExample(typeExample);
        return list;
    }

    /**
     * 获取商品类型及该商品类型下的商品数量
     *
     * @param placeId
     * @return
     */
    public List<RespPlaceGoodsVo> getGoodsTypeAndGoodsCount(Integer placeId) {
        ReqPlaceGoodsTypeVo vo=new ReqPlaceGoodsTypeVo();
        List<RespPlaceGoodsVo> respVoList=new ArrayList<>();
        vo.setPlaceId(placeId);
        List<TbBizPlaceGoodsType> list=this.getPlaceGoodsTypeData(vo);
        if (list!=null&&list.size()>0){
            for (TbBizPlaceGoodsType typeVo:list){
                RespPlaceGoodsVo respVo=new RespPlaceGoodsVo();
                int goodsCount= vPlaceGoodsMapper.getPlaceGoodsCountByTwoTypeId(placeId,typeVo.getId());
                respVo.setGoodsCount(goodsCount);
                respVo.setTwoLevel(typeVo.getName());
                respVo.setTwoLevelId(typeVo.getId());
                respVoList.add(respVo);
            }
        }
        return respVoList;
    }



    /**
     * 获取商品类型（分页）
     * @param reqPlaceGoodsTypeVo
     */
 /*   @Override
    public PageObj<List<TbBizPlaceGoodsType>> getPlaceGoodsTypeList(ReqPlaceGoodsTypeVo reqPlaceGoodsTypeVo) {
        Integer pageNum = 0;
        Integer pageSize = Constants.DEFAULT_PAGE_SIZE;
        TbBizPlaceGoodsTypeExample typeExample =new TbBizPlaceGoodsTypeExample();
        TbBizPlaceGoodsTypeExample.Criteria criteria=typeExample.createCriteria();
        pageNum=reqPlaceGoodsTypeVo.getPageNum();
        pageSize=reqPlaceGoodsTypeVo.getPageSize();
        if (!StringUtils.isEmpty(reqPlaceGoodsTypeVo.getTypeName())){
            criteria.andNameEqualTo("%"+reqPlaceGoodsTypeVo.getTypeName()+"%");
        }
       // criteria.andPlaceIdEqualTo(reqPlaceGoodsTypeVo.getPlaceId());
        int total=tbBizPlaceGoodsTypeMapper.countByExample(typeExample);
        typeExample.setPage(new Page(pageNum * pageSize, pageSize, total));
        List<TbBizPlaceGoodsType> list=tbBizPlaceGoodsTypeMapper.selectByExample(typeExample);
        PageObj<List<TbBizPlaceGoodsType>> result=PageObj.create(total,pageNum,pageSize,list);
        return result;
    }*/

    /**
     * 获取商品类型（分页）
     *
     * @param reqPlaceGoodsTypeVo
     */
    @Override
    public PageObj<List<RespPlaceGoodsTypeVo>> getPlaceGoodsTypeList(ReqPlaceGoodsTypeVo reqPlaceGoodsTypeVo) {
        Integer pageNum = 0;
        Integer pageSize = Constants.DEFAULT_PAGE_SIZE;
        TbBizPlaceGoodsTypeExample typeExample = new TbBizPlaceGoodsTypeExample();
        TbBizPlaceGoodsTypeExample.Criteria criteria = typeExample.createCriteria();
        if (reqPlaceGoodsTypeVo.getPageNum() == null) {
            reqPlaceGoodsTypeVo.setPageNum(pageNum);
        }
        if (reqPlaceGoodsTypeVo.getPageSize() == null) {
            reqPlaceGoodsTypeVo.setPageSize(pageSize);
        }
        if (!StringUtils.isEmpty(reqPlaceGoodsTypeVo.getTwoLevel())) {
            criteria.andNameLike("%" + reqPlaceGoodsTypeVo.getTwoLevel() + "%");
        }
        criteria.andPlaceIdEqualTo(reqPlaceGoodsTypeVo.getPlaceId());
        criteria.andIsDeleteEqualTo(Constants.ZERO);
        int total = tbBizPlaceGoodsTypeMapper.countByExample(typeExample);
        typeExample.setPage(new Page(reqPlaceGoodsTypeVo.getPageNum() * reqPlaceGoodsTypeVo.getPageSize(), reqPlaceGoodsTypeVo.getPageSize(), total));
        List<TbBizPlaceGoodsType> list = tbBizPlaceGoodsTypeMapper.selectByExample(typeExample);

        List<RespPlaceGoodsTypeVo> respList = new ArrayList<>();
        for (TbBizPlaceGoodsType vo : list) {
            RespPlaceGoodsTypeVo respVo = new RespPlaceGoodsTypeVo();
            if (vo.getLevel() != null) {
                //  TbBizPlaceGoodsType  typeVo= getGoodsTypeNameByTypeId(vo.getLevel(),reqPlaceGoodsTypeVo.getPlaceId());
                List<Dict> dicList = getOneLevel(vo.getLevel().toString());
                if (dicList != null && dicList.size() > 0) {
                    respVo.setOneLevel(dicList.get(0).getDataValue());
                }
                respVo.setOneLevelId(vo.getLevel());
                respVo.setTwoLevel(vo.getName());
                respVo.setTwoLevelId(vo.getId());
            } else {
                respVo.setTwoLevel(vo.getName());
                respVo.setTwoLevelId(vo.getId());
            }
            respVo.setId(vo.getId());
            respList.add(respVo);
        }
        PageObj<List<RespPlaceGoodsTypeVo>> result = PageObj.create(total, reqPlaceGoodsTypeVo.getPageNum(), reqPlaceGoodsTypeVo.getPageSize(), respList);
        return result;
    }

    /**
     * 更新商品类型
     *
     * @param reqPlaceGoodsTypeVo
     */
    @Override
    public APIResponse updatePlaceGoodsTypeData(ReqPlaceGoodsTypeVo reqPlaceGoodsTypeVo) {
        /*TbBizPlaceGoodsTypeExample typeExample =new TbBizPlaceGoodsTypeExample();
        TbBizPlaceGoodsTypeExample.Criteria criteria=typeExample.createCriteria();
        criteria.andPlaceIdEqualTo(reqPlaceGoodsTypeVo.getPlaceId());
        criteria.andNameEqualTo(reqPlaceGoodsTypeVo.getTwoLevel().trim());
        List<TbBizPlaceGoodsType> list=tbBizPlaceGoodsTypeMapper.selectByExample(typeExample);
        if (list.size()>0){
            return APIResponse.returnFail("该商品类型名称已存在!");
        }*/

        TbBizPlaceGoodsType type = new TbBizPlaceGoodsType();

        TbBizPlaceGoodsType info=this.checkTypeName(null,reqPlaceGoodsTypeVo.getTwoLevel(),reqPlaceGoodsTypeVo.getId());
        if (info==null){
            TbBizPlaceGoodsType val=this.checkTypeName(reqPlaceGoodsTypeVo.getPlaceId(),reqPlaceGoodsTypeVo.getTwoLevel(),null);
            if (val!=null){
                return APIResponse.returnFail("该商品类型名称已存在!");
            }
        }
        type.setLevel(reqPlaceGoodsTypeVo.getOneLevelId());
        type.setId(reqPlaceGoodsTypeVo.getId());
        type.setName(reqPlaceGoodsTypeVo.getTwoLevel().trim());
        tbBizPlaceGoodsTypeMapper.updateByPrimaryKeySelective(type);
        return APIResponse.returnSuccess();
    }

  /*  @Override
    public APIResponse updatePlaceGoodsTypeDatassss(ReqPlaceGoodsTypeVo reqPlaceGoodsTypeVo) {
        TbBizPlaceGoodsTypeExample typeExample =new TbBizPlaceGoodsTypeExample();
        TbBizPlaceGoodsTypeExample.Criteria criteria=typeExample.createCriteria();
        criteria.andPlaceIdEqualTo(reqPlaceGoodsTypeVo.getPlaceId());
        criteria.andIdEqualTo(reqPlaceGoodsTypeVo.getId());
        List<TbBizPlaceGoodsType> list=tbBizPlaceGoodsTypeMapper.selectByExample(typeExample);
        if (list.size()>0){
            return APIResponse.returnFail("该商品类型名称已存在!");
        }
        TbBizPlaceGoodsType type=new TbBizPlaceGoodsType();
        type.setId(reqPlaceGoodsTypeVo.getId());
        type.setName(reqPlaceGoodsTypeVo.getTypeName().trim());
        type.setLevel(reqPlaceGoodsTypeVo.getOneLevelId());
        tbBizPlaceGoodsTypeMapper.updateByPrimaryKeySelective(type);
        return APIResponse.returnSuccess();
    }
*/

    /**
     * 获取商品类别
     *
     * @param typeId
     * @param placeId
     * @return
     */
    @Override
    public List<TbBizPlaceGoodsType> getGoodsTypeNameByTypeId(Integer typeId, Integer placeId) {
        TbBizPlaceGoodsTypeExample example = new TbBizPlaceGoodsTypeExample();
        TbBizPlaceGoodsTypeExample.Criteria criteria = example.createCriteria();
        if (typeId != null) {
            criteria.andIdEqualTo(typeId);
        }
        if (placeId != null) {
            criteria.andPlaceIdEqualTo(placeId);
        }
        List<TbBizPlaceGoodsType> typeList = tbBizPlaceGoodsTypeMapper.selectByExample(example);
        return typeList;
    }


    /**
     * 获取商品类别ID通过商品名称
     *
     * @param name
     * @param
     * @return
     */

    public TbBizPlaceGoodsType getGoodsTypeTypeIdByName(String name, Integer placeId) {
        TbBizPlaceGoodsTypeExample example = new TbBizPlaceGoodsTypeExample();
        TbBizPlaceGoodsTypeExample.Criteria criteria = example.createCriteria();
        criteria.andNameEqualTo(name.trim());
        criteria.andPlaceIdEqualTo(placeId);
        List<TbBizPlaceGoodsType> nameList = tbBizPlaceGoodsTypeMapper.selectByExample(example);
        if (nameList != null && nameList.size() > 0) {
            return nameList.get(0);
        } else {
            return null;
        }
    }

    public APIResponse checkGoodsInventory(List<ReqPlaceGoodsVo> goodsList){
    if (goodsList!=null){
        for (ReqPlaceGoodsVo gVo:goodsList) {
            TbBizPlaceGoods goods= tbBizPlaceGoodsMapper.selectByPrimaryKey(gVo.getId());
            if(goods.getInventory()<gVo.getGoodsCount()){
                return APIResponse.returnFail(goods.getName()+"库存不足");
            }
        }
    }
        return APIResponse.returnSuccess();
    }
    /**
     * 提交商品订单
     *
     * @param reqPlaceGoodsVo
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public APIResponse submitGoodsOrder(ReqPlaceGoodsVo reqPlaceGoodsVo) throws java.lang.Exception {
       if (StringUtils.isEmpty(reqPlaceGoodsVo)){
           return APIResponse.returnFail("参数不能为空！");
       }

        if (StringUtils.isEmpty(reqPlaceGoodsVo.getUid())) {
            return APIResponse.returnFail("Uid不能为空！");
        }
        //校验库存
        APIResponse resp=this.checkGoodsInventory(reqPlaceGoodsVo.getGoodsList());
        if (resp.isRet()==false){
            return resp;
        }
        String orderNo = CommonUtils.generateBusinessOrderNo(Constants.PLACE_SYSTEM, reqPlaceGoodsVo.getUid());
        BigDecimal price = new BigDecimal(0);
        BigDecimal memberPrice = new BigDecimal(0);
        BigDecimal memberTotalPrice = new BigDecimal(0);//会员总价
        BigDecimal generalTotalPrice = new BigDecimal(0);//普通总价
        //订单明细
        List<ReqPlaceGoodsVo> reqGoodsList = reqPlaceGoodsVo.getGoodsList();
        Integer memberUid = placeTicketService.getUidByPhone(reqPlaceGoodsVo.getMobile());
        List goodsIds = new ArrayList<>();
        for (ReqPlaceGoodsVo vo : reqGoodsList) {
            goodsIds.add(vo.getGoodsId());
        }
        TbBizPlaceGoodsExample example = new TbBizPlaceGoodsExample();
        TbBizPlaceGoodsExample.Criteria criteria = example.createCriteria();
        criteria.andGoodsIdIn(goodsIds);
        List<TbBizPlaceGoods> tbBizPlaceGoodsList = tbBizPlaceGoodsMapper.selectByExample(example);
        //取商品价格
        for (ReqPlaceGoodsVo req : reqGoodsList) {
            for (TbBizPlaceGoods tbBizPlaceGood : tbBizPlaceGoodsList) {
                if (req.getId().intValue() == tbBizPlaceGood.getId()) {
                    req.setMemberPrice(tbBizPlaceGood.getMemberPrice());
                    req.setSalePrice(tbBizPlaceGood.getSalePrice());
                    memberTotalPrice = memberTotalPrice.add(req.getMemberPrice().multiply(new BigDecimal(req.getGoodsCount())));
                    generalTotalPrice = generalTotalPrice.add(req.getSalePrice().multiply(new BigDecimal(req.getGoodsCount())));
                }
            }
        }
        //取商品普通价
            /*for (ReqPlaceGoodsVo req:reqGoodsList){
                for (TbBizPlaceGoods tbBizPlaceGood : tbBizPlaceGoodsList){
                    if (req.getId().intValue() == tbBizPlaceGood.getId()){
                        req.setSalePrice(tbBizPlaceGood.getSalePrice());
                    }
                }
            }*/
        StringBuffer goodsStr = new StringBuffer(" ");
        BigDecimal totalDebit = new BigDecimal(0);
        BigDecimal lastBeforeAmount = new BigDecimal(0);
        int index = 0;
        BigDecimal sumPrice = new BigDecimal(0);
        List<TbBizPlaceOrderItem> orderItemList = new ArrayList<>();
        for (ReqPlaceGoodsVo req : reqGoodsList) {
            index++;
            TbBizPlaceGoods goods = tbBizPlaceGoodsMapper.selectByPrimaryKey(req.getId());
            goodsStr = goodsStr.append(goods.getName()).append("*").append(req.getGoodsCount()).append(";" + " ");
            totalDebit = totalDebit.add(req.getSalePrice().multiply(new BigDecimal(req.getGoodsCount())).setScale(2, BigDecimal.ROUND_HALF_UP));

//            //更新商品库存
//            TbBizPlaceGoods goodsVo=tbBizPlaceGoodsMapper.selectByPrimaryKey(req.getId());
//            int counts=goodsVo.getInventory().intValue() - req.getGoodsCount().intValue();
//            TbBizPlaceGoods vo=new TbBizPlaceGoods();
//            vo.setId(req.getId());
//            vo.setInventory(counts);
//            tbBizPlaceGoodsMapper.updateByPrimaryKeySelective(vo);
            //会员卡购买支付总价格是商品会员价格之和，散客购买支付总价格是商品普通价格之和
            if (StringUtils.isEmpty(reqPlaceGoodsVo.getMemberCardId())) {
                price = price.add(req.getSalePrice().multiply(new BigDecimal(req.getGoodsCount())).setScale(2, BigDecimal.ROUND_HALF_UP));
            } else {
                price = price.add(req.getMemberPrice().multiply(new BigDecimal(req.getGoodsCount())).setScale(2, BigDecimal.ROUND_HALF_UP));
            }
            //插入明细
            TbBizPlaceOrderItem item = new TbBizPlaceOrderItem();
            item.setPlaceOrderId(orderNo);
            item.setUnitSalePlanId(req.getId());//商品主键
            item.setSaleId(req.getGoodsId());//商品UUID
            item.setItemType(PlaceConstants.PLACE_GOODS_TYPE); //订单明细类型
            item.setConsumeTime(new Date());

            item.setItemUuid(UUIDUtils.createId());
            item.setUseType(PlaceConstants.ORDER_USE_GOODS);
            item.setGoodsId(req.getId());
            item.setGoodsName(goods.getName());
            item.setOriginPrice(goods.getSalePrice());
            item.setMemberPrice(goods.getMemberPrice());
            //如果是用会员卡购买，订单明细存的实际价格是商品会员价格，如果是散客购买，订单明细存的实际价格是商品普通价格
            BigDecimal data = new BigDecimal(0);
            if (StringUtils.isEmpty(reqPlaceGoodsVo.getMemberCardId())) {
                int result = generalTotalPrice.compareTo(reqPlaceGoodsVo.getReceivedAmount());
                //如果有改价
                if (result != 0) {
                    BigDecimal total = req.getSalePrice().multiply(new BigDecimal(req.getGoodsCount()));
                    BigDecimal salePriceRate = total.divide(reqPlaceGoodsVo.getTotalAmount(), 6, BigDecimal.ROUND_HALF_EVEN);
                    BigDecimal total2 = reqPlaceGoodsVo.getReceivedAmount().multiply(salePriceRate).setScale(2, BigDecimal.ROUND_HALF_UP);
                    data = data.add(total2);
                    //以防四舍五入后导致实付金额总额不精确，最后一个金额等于实付金额减去前面金额的总和
                    if (index == reqGoodsList.size()) {
                        data = reqPlaceGoodsVo.getReceivedAmount().subtract(sumPrice);
                    } else {
                        sumPrice = sumPrice.add(data);
                    }
                    //除不尽，或小数点后有三位小数，则均摊
                    if (!PlaceUtil.check(data.doubleValue(), req.getGoodsCount()) || PlaceUtil.checkNum(data.doubleValue(), req.getGoodsCount()) > 2) {
                        count(data, orderNo, req, orderItemList);
                    } else {
                        item.setSurplusGoodsCount(req.getGoodsCount());
                        item.setTotalGoodsCount(req.getGoodsCount());
                        item.setTicketCount(req.getGoodsCount());//商品数量
                        item.setCreateUid(req.getUid());
                        item.setSalePrice(data.divide(new BigDecimal(req.getGoodsCount().intValue()), 2, BigDecimal.ROUND_HALF_EVEN));
                        orderItemList.add(item);
                        tbBizPlaceOrderItemMapper.insert(item);
                    }
                } else {//如果没改价
                    item.setSurplusGoodsCount(req.getGoodsCount());
                    item.setTotalGoodsCount(req.getGoodsCount());
                    item.setTicketCount(req.getGoodsCount());//商品数量
                    item.setCreateUid(req.getUid());
                    item.setSalePrice(req.getSalePrice());
                    orderItemList.add(item);
                    tbBizPlaceOrderItemMapper.insert(item);
                }
            } else {
                int result = memberTotalPrice.compareTo(reqPlaceGoodsVo.getReceivedAmount());
                //如果有改价
                if (result != 0) {
                    BigDecimal total = req.getMemberPrice().multiply(new BigDecimal(req.getGoodsCount()));
                    BigDecimal memberPriceRate = total.divide(reqPlaceGoodsVo.getTotalAmount(), 6, BigDecimal.ROUND_HALF_EVEN);
                    BigDecimal total2 = reqPlaceGoodsVo.getReceivedAmount().multiply(memberPriceRate).setScale(2, BigDecimal.ROUND_HALF_UP);
                    data = data.add(total2);
                    //以防四舍五入后导致实付金额总额不精确，最后一个金额等于实付金额减去前面金额的总和
                    if (index == reqGoodsList.size()) {
                        data = reqPlaceGoodsVo.getReceivedAmount().subtract(sumPrice);
                    } else {
                        sumPrice = sumPrice.add(data);
                    }
                    //除不尽，或小数点后有三位小数，则均摊
                    if (!PlaceUtil.check(data.doubleValue(), req.getGoodsCount()) || PlaceUtil.checkNum(data.doubleValue(), req.getGoodsCount()) > 2) {
                        count(data, orderNo, req, orderItemList);
                    } else {
                        item.setSurplusGoodsCount(req.getGoodsCount());
                        item.setTotalGoodsCount(req.getGoodsCount());
                        item.setTicketCount(req.getGoodsCount());//商品数量
                        item.setCreateUid(req.getUid());
                        item.setSalePrice(data.divide(new BigDecimal(req.getGoodsCount().intValue()), 2, BigDecimal.ROUND_HALF_EVEN));
                        orderItemList.add(item);
                        tbBizPlaceOrderItemMapper.insert(item);
                    }
                } else {//如果没改价
                    item.setSurplusGoodsCount(req.getGoodsCount());
                    item.setTotalGoodsCount(req.getGoodsCount());
                    item.setTicketCount(req.getGoodsCount());//商品数量
                    item.setCreateUid(req.getUid());
                    item.setSalePrice(req.getMemberPrice());
                    orderItemList.add(item);
                    tbBizPlaceOrderItemMapper.insert(item);
                }

            }
          /*  item.setTicketCount(req.getGoodsCount());//商品数量
            item.setCreateUid(req.getUid());
            tbBizPlaceOrderItemMapper.insert(item);*/
            logger.debug("===================插入明细数据:TbBizPlaceOrderItem:{}", JSON.toJSONString(item));
        }
        //插入订单信息
        TbBizPlaceOrder order = new TbBizPlaceOrder();
        order.setPlaceOrderId(orderNo);
        order.setPlaceId(reqPlaceGoodsVo.getPlaceId());
        order.setDate(new Date());
        order.setDebit(totalDebit);
        order.setHandAdjustAmount(reqPlaceGoodsVo.getReceivedAmount().subtract(price));
        order.setOrderTime(new Date());
        order.setEndTime(new Date());
        order.setPaymentTime(new Date());
        order.setOrderStatusChangeDate(new Date());
        order.setPayStatus((byte) 2);
        order.setOrderStatus((byte) 3);
        if (!StringUtils.isEmpty(reqPlaceGoodsVo.getMobile())) {
            order.setUid(placeMemberService.getUidByNameAndPhone(null, reqPlaceGoodsVo.getMobile()));
        } else {
            order.setUid(null);
        }
        order.setMobile(reqPlaceGoodsVo.getMobile());
        order.setUseType((byte) 4);
        order.setPlatform(5);
        order.setIsEffective((byte) 1);
        order.setSourceType((byte) 2);
        order.setDescrible(reqPlaceGoodsVo.getDescribe());
        order.setCreateUid(reqPlaceGoodsVo.getUid());
        order.setCustomerName(org.apache.commons.lang3.StringUtils.isEmpty(reqPlaceGoodsVo.getName()) ? "散客" : reqPlaceGoodsVo.getName());
        order.setExpression(reqPlaceGoodsVo.getExpression());
        order.setOrderChannel(PlaceConstants.PLACE_ADMIN_PAY_TYPE.byteValue());
        TbBizPlaceMemberCard tbBizPlaceMemberCard = null;
        if (StringUtils.isEmpty(reqPlaceGoodsVo.getMemberCardId())) {
            order.setIsMember(PlaceConstants.NO);
        } else {
            tbBizPlaceMemberCard = placeMemberService.getTbBizPlaceMemberCardById(reqPlaceGoodsVo.getMemberCardId());
            if (!StringUtils.isEmpty(tbBizPlaceMemberCard)) {
                order.setIsMember(PlaceConstants.YES);
                order.setInnerCardNo(tbBizPlaceMemberCard.getInnerCardNo());
            }
        }
        //场馆运营模式
        TbBizPlace tbBizPlace = tbBizPlaceMapper.selectByPrimaryKey(reqPlaceGoodsVo.getPlaceId());
        order.setBusinessMode(tbBizPlace.getBusinessMode());

        tbBizPlaceOrderMapper.insertSelective(order);
        logger.debug("========================插入订单数据:TbBizPlaceOrder:{}", JSON.toJSONString(order));

        //插入支付明细
        TbBizPlacePayItem tbBizPlacePayItem = new TbBizPlacePayItem();
        tbBizPlacePayItem.setPlaceOrderId(orderNo);
        //实付金额不为空，则明细支付插入实付金额
        tbBizPlacePayItem.setAmount(reqPlaceGoodsVo.getReceivedAmount());
        tbBizPlacePayItem.setAmountType(PlaceConstants.DEBIT_TYPE);
        tbBizPlacePayItem.setPayType(reqPlaceGoodsVo.getAdminPayType());
        tbBizPlacePayItem.setAdminPayType(PayTypeEnum.getEnum(reqPlaceGoodsVo.getAdminPayType()).getUnifiedId());
        tbBizPlacePayItemMapper.insert(tbBizPlacePayItem);
        logger.debug("========================插入订单支付数据:TbBizPlacePayItem:{}",
                JSON.toJSONString(tbBizPlacePayItem));

        APIResponse apiResponse = null;
        if (!StringUtils.isEmpty(reqPlaceGoodsVo.getMemberCardId())) {
            TbBizPlaceMemberCardType cardtypeVo = placeMemberService.getMemberTypeById(tbBizPlaceMemberCard.getCardTypeId());
            //会员卡扣钱
            try {
                //实付金额不为空，则会员卡消费扣取相应的实付金额
                saleGoodsMemberCardOp(reqPlaceGoodsVo, tbBizPlaceMemberCard, cardtypeVo, reqPlaceGoodsVo.getReceivedAmount(), orderNo, goodsStr.toString());

            } catch (Exception e) {
                throw e;
            }
        }
        //减库存
        this.updateGoodsInventory(orderItemList, order);

        //插入支付流水
        ReqOrderHistory reqOrderHistory = placeOrderUtilService.tbBizPlaceOrder2ReqOrderHistory(order, reqPlaceGoodsVo.getReceivedAmount(), (byte) 0, (byte) 0);
        placeOrderUtilService.insertOrderHistory(reqOrderHistory);
        PlacePrintVo placePrintVo = new PlacePrintVo();
        if (!StringUtils.isEmpty(reqPlaceGoodsVo.getMemberCardId())) {
            placePrintVo.setIsMember(PlaceConstants.YES);
        } else {
            placePrintVo.setIsMember(PlaceConstants.NO);
        }
        placePrintVo.setBusinessType(PlaceConstants.ORDER_USE_GOODS);
        placePrintVo.setPlaceOrderId(order.getPlaceOrderId());
        return APIResponse.returnSuccess(placeOrderUtilService.getPrintOrderInfo(placePrintVo));
    }

    public void count(BigDecimal data, String orderNo, ReqPlaceGoodsVo req, List<TbBizPlaceOrderItem> orderItemList) {
        List<TbBizPlaceOrderItem> listItems = new ArrayList<>();
        List<TbBizPlaceOrderItem> sVo = new ArrayList<>();
        List<TbBizPlaceOrderItem> dVo = new ArrayList<>();
        for (int i = 0; i < req.getGoodsCount(); i++) {
            BigDecimal value = new BigDecimal(0);
            if (req.getGoodsCount().intValue() != i) {
                TbBizPlaceOrderItem tvo = new TbBizPlaceOrderItem();
                tvo.setPlaceOrderId(orderNo);
                tvo.setUnitSalePlanId(req.getId());//商品主键
                tvo.setSaleId(req.getGoodsId());//商品UUID
                tvo.setItemType(PlaceConstants.PLACE_GOODS_TYPE); //订单明细类型
                tvo.setConsumeTime(new Date());
                value = data.divide(new BigDecimal(req.getGoodsCount().intValue() - i), 2, BigDecimal.ROUND_HALF_EVEN);
                logger.info("value---->" + value);
                data = data.subtract(value);
                tvo.setTicketCount(1);//商品数量
                tvo.setCreateUid(req.getUid());
                tvo.setSalePrice(value);

                tvo.setItemUuid(UUIDUtils.createId());
                tvo.setUseType(PlaceConstants.ORDER_USE_GOODS);
                tvo.setGoodsId(req.getId());
                TbBizPlaceGoods goods = tbBizPlaceGoodsMapper.selectByPrimaryKey(req.getId());
                tvo.setGoodsName(goods.getName());
                tvo.setSurplusGoodsCount(1);
                tvo.setTotalGoodsCount(1);
                tvo.setOriginPrice(goods.getSalePrice());
                tvo.setMemberPrice(goods.getMemberPrice());
                listItems.add(tvo);
                //tbBizPlaceOrderItemMapper.insert(tvo);
            }
        }
        //合并价格重复的订单
        for (int i = 0; i < listItems.size(); i++) {
            BigDecimal salePrice = listItems.get(0).getSalePrice();
            if (salePrice.equals(listItems.get(i).getSalePrice())) {
                sVo.add(listItems.get(i));
            } else {
                dVo.add(listItems.get(i));
            }
        }
        if (sVo != null && sVo.size() > 0) {
            TbBizPlaceOrderItem orderItem = sVo.get(0);
            orderItem.setTicketCount(sVo.size());
            orderItem.setSurplusGoodsCount(sVo.size());
            orderItem.setTotalGoodsCount(sVo.size());
            tbBizPlaceOrderItemMapper.insert(orderItem);
            if (orderItemList != null) {
                orderItemList.add(orderItem);
            }
        }
        if (dVo != null && dVo.size() > 0) {
            TbBizPlaceOrderItem orderItemdvo = dVo.get(0);
            orderItemdvo.setTicketCount(dVo.size());
            orderItemdvo.setSurplusGoodsCount(dVo.size());
            orderItemdvo.setTotalGoodsCount(dVo.size());
            tbBizPlaceOrderItemMapper.insert(orderItemdvo);
            if (orderItemList != null) {
                orderItemList.add(orderItemdvo);
            }
        }
        //tbBizPlaceOrderItemMapper.insert(item);
    }

    /**
     * 提交商品订单(扫码支付)
     *
     * @param reqPlaceGoodsVo
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public APIResponse submitGoodsOrderForScanPay(ReqPlaceGoodsVo reqPlaceGoodsVo, PlaceOrderServiceWrapper placeOrderServiceWrapper) throws java.lang.Exception {
        if (StringUtils.isEmpty(reqPlaceGoodsVo)){
            return APIResponse.returnFail("参数不能为空！");
        }
        if (StringUtils.isEmpty(reqPlaceGoodsVo.getUid())) {
            return APIResponse.returnFail("Uid不能为空！");
        }
        //校验库存
        APIResponse resp= this.checkGoodsInventory(reqPlaceGoodsVo.getGoodsList());
        if (resp.isRet()==false){
            return resp;
        }
        String orderNo = CommonUtils.generateBusinessOrderNo(Constants.PLACE_SYSTEM, reqPlaceGoodsVo.getUid());
        BigDecimal price = new BigDecimal(0);
        BigDecimal memberPrice = new BigDecimal(0);
        BigDecimal memberTotalPrice = new BigDecimal(0);//会员总价
        BigDecimal generalTotalPrice = new BigDecimal(0);//普通总价
        //订单明细
        List<ReqPlaceGoodsVo> reqGoodsList = reqPlaceGoodsVo.getGoodsList();
        Integer memberUid = placeTicketService.getUidByPhone(reqPlaceGoodsVo.getMobile());
        List goodsIds = new ArrayList<>();
        for (ReqPlaceGoodsVo vo : reqGoodsList) {
            goodsIds.add(vo.getGoodsId());
        }
        TbBizPlaceGoodsExample example = new TbBizPlaceGoodsExample();
        TbBizPlaceGoodsExample.Criteria criteria = example.createCriteria();
        criteria.andGoodsIdIn(goodsIds);
        List<TbBizPlaceGoods> tbBizPlaceGoodsList = tbBizPlaceGoodsMapper.selectByExample(example);
        //取商品价格
        for (ReqPlaceGoodsVo req : reqGoodsList) {
            for (TbBizPlaceGoods tbBizPlaceGood : tbBizPlaceGoodsList) {
            	//增加商品库存不足处理
            	if(tbBizPlaceGood.getInventory()==0){
            		return  APIResponse.returnFail(tbBizPlaceGood.getName()+"库存不足");
            	}
                if (req.getId().intValue() == tbBizPlaceGood.getId()) {
                    req.setMemberPrice(tbBizPlaceGood.getMemberPrice());
                    req.setSalePrice(tbBizPlaceGood.getSalePrice());
                    memberTotalPrice = memberTotalPrice.add(req.getMemberPrice().multiply(new BigDecimal(req.getGoodsCount())));
                    generalTotalPrice = generalTotalPrice.add(req.getSalePrice().multiply(new BigDecimal(req.getGoodsCount())));
                }
            }
        }
        //取商品普通价
       /* for (ReqPlaceGoodsVo req:reqGoodsList){
            for (TbBizPlaceGoods tbBizPlaceGood : tbBizPlaceGoodsList){
                if (req.getId().intValue() == tbBizPlaceGood.getId()){
                    req.setSalePrice(tbBizPlaceGood.getSalePrice());
                }
            }
        }*/
        StringBuffer goodsStr = new StringBuffer(" ");
        BigDecimal totalDebit = new BigDecimal(0);
        BigDecimal lastBeforeAmount = new BigDecimal(0);
        int index = 0;
        BigDecimal sumPrice = new BigDecimal(0);
        for (ReqPlaceGoodsVo req : reqGoodsList) {
            index++;
            TbBizPlaceGoods goods = tbBizPlaceGoodsMapper.selectByPrimaryKey(req.getId());
            goodsStr = goodsStr.append(goods.getName()).append("*").append(req.getGoodsCount()).append(";" + " ");
            totalDebit = totalDebit.add(req.getSalePrice().multiply(new BigDecimal(req.getGoodsCount())).setScale(2, BigDecimal.ROUND_HALF_UP));

            //会员卡购买支付总价格是商品会员价格之和，散客购买支付总价格是商品普通价格之和
            if (StringUtils.isEmpty(reqPlaceGoodsVo.getMemberCardId())) {
                price = price.add(req.getSalePrice().multiply(new BigDecimal(req.getGoodsCount())).setScale(2, BigDecimal.ROUND_HALF_UP));
            } else {
                price = price.add(req.getMemberPrice().multiply(new BigDecimal(req.getGoodsCount())).setScale(2, BigDecimal.ROUND_HALF_UP));
            }
            //插入明细
            TbBizPlaceOrderItem item = new TbBizPlaceOrderItem();
            item.setPlaceOrderId(orderNo);
            item.setUnitSalePlanId(req.getId());//商品主键
            item.setSaleId(req.getGoodsId());//商品UUID
            item.setItemType(PlaceConstants.PLACE_GOODS_TYPE); //订单明细类型
            item.setConsumeTime(new Date());

            item.setItemUuid(UUIDUtils.createId());
            item.setUseType(PlaceConstants.ORDER_USE_GOODS);
            item.setGoodsId(req.getId());
            item.setGoodsName(goods.getName());
            item.setOriginPrice(goods.getSalePrice());
            item.setMemberPrice(goods.getMemberPrice());
            //如果是用会员卡购买，订单明细存的实际价格是商品会员价格，如果是散客购买，订单明细存的实际价格是商品普通价格
            BigDecimal data = new BigDecimal(0);
            if (StringUtils.isEmpty(reqPlaceGoodsVo.getMemberCardId())) {
                int result = generalTotalPrice.compareTo(reqPlaceGoodsVo.getReceivedAmount());
                //如果有改价
                if (result != 0) {
                    BigDecimal total = req.getSalePrice().multiply(new BigDecimal(req.getGoodsCount()));
                    BigDecimal salePriceRate = total.divide(reqPlaceGoodsVo.getTotalAmount(), 6, BigDecimal.ROUND_HALF_EVEN);
                    BigDecimal total2 = reqPlaceGoodsVo.getReceivedAmount().multiply(salePriceRate).setScale(2, BigDecimal.ROUND_HALF_UP);
                    data = data.add(total2);
                    //以防四舍五入后导致实付金额总额不精确，最后一个金额等于实付金额减去前面金额的总和
                    if (index == reqGoodsList.size()) {
                        data = reqPlaceGoodsVo.getReceivedAmount().subtract(sumPrice);
                    } else {
                        sumPrice = sumPrice.add(data);
                    }
                    //除不尽，或小数点后有三位小数，则均摊
                    if (!PlaceUtil.check(data.doubleValue(), req.getGoodsCount()) || PlaceUtil.checkNum(data.doubleValue(), req.getGoodsCount()) > 2) {
                        count(data, orderNo, req, null);
                    } else {
                        item.setSurplusGoodsCount(req.getGoodsCount());
                        item.setTotalGoodsCount(req.getGoodsCount());
                        item.setTicketCount(req.getGoodsCount());//商品数量
                        item.setCreateUid(req.getUid());
                        item.setSalePrice(data.divide(new BigDecimal(req.getGoodsCount().intValue()), 2, BigDecimal.ROUND_HALF_EVEN));
                        tbBizPlaceOrderItemMapper.insert(item);
                    }
                } else {//如果没改价
                    item.setSurplusGoodsCount(req.getGoodsCount());
                    item.setTotalGoodsCount(req.getGoodsCount());
                    item.setTicketCount(req.getGoodsCount());//商品数量
                    item.setCreateUid(req.getUid());
                    item.setSalePrice(req.getSalePrice());
                    tbBizPlaceOrderItemMapper.insert(item);
                }
            } else {
                int result = memberTotalPrice.compareTo(reqPlaceGoodsVo.getReceivedAmount());
                //如果有改价
                if (result != 0) {
                    BigDecimal total = req.getMemberPrice().multiply(new BigDecimal(req.getGoodsCount()));
                    BigDecimal memberPriceRate = total.divide(reqPlaceGoodsVo.getTotalAmount(), 6, BigDecimal.ROUND_HALF_EVEN);
                    BigDecimal total2 = reqPlaceGoodsVo.getReceivedAmount().multiply(memberPriceRate).setScale(2, BigDecimal.ROUND_HALF_UP);
                    data = data.add(total2);
                    //以防四舍五入后导致实付金额总额不精确，最后一个金额等于实付金额减去前面金额的总和
                    if (index == reqGoodsList.size()) {
                        data = reqPlaceGoodsVo.getReceivedAmount().subtract(sumPrice);
                    } else {
                        sumPrice = sumPrice.add(data);
                    }
                    //除不尽，或小数点后有三位小数，则均摊
                    if (!PlaceUtil.check(data.doubleValue(), req.getGoodsCount()) || PlaceUtil.checkNum(data.doubleValue(), req.getGoodsCount()) > 2) {
                        count(data, orderNo, req, null);
                    } else {
                        item.setSurplusGoodsCount(req.getGoodsCount());
                        item.setTotalGoodsCount(req.getGoodsCount());
                        item.setTicketCount(req.getGoodsCount());//商品数量
                        item.setCreateUid(req.getUid());
                        item.setSalePrice(data.divide(new BigDecimal(req.getGoodsCount().intValue()), 2, BigDecimal.ROUND_HALF_EVEN));
                        tbBizPlaceOrderItemMapper.insert(item);
                    }
                } else {//如果没改价
                    item.setSurplusGoodsCount(req.getGoodsCount());
                    item.setTotalGoodsCount(req.getGoodsCount());
                    item.setTicketCount(req.getGoodsCount());//商品数量
                    item.setCreateUid(req.getUid());
                    item.setSalePrice(req.getMemberPrice());
                    tbBizPlaceOrderItemMapper.insert(item);
                }
            }

          /*  item.setTicketCount(req.getGoodsCount());//商品数量
            item.setCreateUid(req.getUid());
            tbBizPlaceOrderItemMapper.insert(item);*/
            logger.debug("===================插入明细数据:TbBizPlaceOrderItem:{}", JSON.toJSONString(item));
        }
        //插入订单信息
        TbBizPlaceOrder order = new TbBizPlaceOrder();
        order.setPlaceOrderId(orderNo);
        order.setPlaceId(reqPlaceGoodsVo.getPlaceId());
        order.setDate(new Date());
        order.setDebit(totalDebit);
        order.setHandAdjustAmount(reqPlaceGoodsVo.getReceivedAmount().subtract(price));
        order.setOrderTime(new Date());
        order.setEndTime(new Date());
        order.setPaymentTime(null);
        order.setOrderStatusChangeDate(new Date());
        if (!StringUtils.isEmpty(reqPlaceGoodsVo.getMobile())) {
            order.setUid(placeMemberService.getUidByNameAndPhone(null, reqPlaceGoodsVo.getMobile()));
        } else {
            order.setUid(null);
        }
        order.setMobile(reqPlaceGoodsVo.getMobile());
        order.setUseType((byte) 4);
        order.setPlatform(5);
        order.setIsEffective((byte) 1);
        order.setSourceType((byte) 2);
        order.setDescrible(reqPlaceGoodsVo.getDescribe());
        order.setCreateUid(reqPlaceGoodsVo.getUid());
        order.setCustomerName(org.apache.commons.lang3.StringUtils.isEmpty(reqPlaceGoodsVo.getName()) ? "散客" : reqPlaceGoodsVo.getName());
        order.setExpression(reqPlaceGoodsVo.getExpression());
        //扫码支付
        order.setOrderStatus(PlaceConstants.NOT_PAY_STATUS);
        order.setPayStatus(PlaceConstants.ORDER_PREPAY_STATUS);
        //场馆运营模式
        TbBizPlace tbBizPlace = tbBizPlaceMapper.selectByPrimaryKey(reqPlaceGoodsVo.getPlaceId());
        order.setBusinessMode(tbBizPlace.getBusinessMode());
        order.setOrderChannel(PlaceConstants.PLACE_ADMIN_PAY_TYPE.byteValue());
        order.setIsMember(PlaceConstants.NO);
        if (PlaceConstants.PLACE_ADMIN_PAY_WAYS_PO_UNIONPAY.equals(reqPlaceGoodsVo.getAdminPayType().toString())){
            order.setIsType(PlaceConstants.YES);
        }
        tbBizPlaceOrderMapper.insertSelective(order);
        logger.debug("========================插入订单数据:TbBizPlaceOrder:{}", JSON.toJSONString(order));

        
        if (!PlaceConstants.PLACE_ADMIN_PAY_WAYS_PO_UNIONPAY.equals(reqPlaceGoodsVo.getAdminPayType().toString())){//非pos生成支付明细
        //插入支付明细
        TbBizPlacePayItem tbBizPlacePayItem = new TbBizPlacePayItem();
        tbBizPlacePayItem.setPlaceOrderId(orderNo);
        //实付金额不为空，则明细支付插入实付金额
        tbBizPlacePayItem.setAmount(reqPlaceGoodsVo.getReceivedAmount());
        tbBizPlacePayItem.setAmountType(PlaceConstants.DEBIT_TYPE);
        tbBizPlacePayItem.setPayType(reqPlaceGoodsVo.getAdminPayType());
        tbBizPlacePayItem.setAdminPayType(PayTypeEnum.getEnum(reqPlaceGoodsVo.getAdminPayType()).getUnifiedId());
        tbBizPlacePayItemMapper.insert(tbBizPlacePayItem);
        logger.debug("========================插入订单支付数据:TbBizPlacePayItem:{}",
                JSON.toJSONString(tbBizPlacePayItem));
        
        }
        	//小商品改为先减库存
        	TbBizPlaceOrderItemExample tbBizPlaceOrderItemExample = new TbBizPlaceOrderItemExample();
            TbBizPlaceOrderItemExample.Criteria tbBizPlaceOrderItemCriteria = tbBizPlaceOrderItemExample.createCriteria();
            tbBizPlaceOrderItemCriteria.andPlaceOrderIdEqualTo(orderNo);
            List<TbBizPlaceOrderItem> tbBizPlaceOrderItemList = tbBizPlaceOrderItemMapper.selectByExample(tbBizPlaceOrderItemExample);
            if (!CollectionUtils.isEmpty(tbBizPlaceOrderItemList)){
                this.updateGoodsInventory(tbBizPlaceOrderItemList,order);
            }
        	
        
        APIResponse apiResponse = null;
        if (!StringUtils.isEmpty(reqPlaceGoodsVo.getMemberCardId())) {
            TbBizPlaceMemberCard tbBizPlaceMemberCard = placeMemberService.getTbBizPlaceMemberCardById(reqPlaceGoodsVo.getMemberCardId());
            TbBizPlaceMemberCardType cardtypeVo = placeMemberService.getMemberTypeById(tbBizPlaceMemberCard.getCardTypeId());
            //会员卡扣钱
            try {
                //实付金额不为空，则会员卡消费扣取相应的实付金额
                saleGoodsMemberCardOp(reqPlaceGoodsVo, tbBizPlaceMemberCard, cardtypeVo, reqPlaceGoodsVo.getReceivedAmount(), orderNo, goodsStr.toString());

            } catch (Exception e) {
                throw e;
            }
        }
        return APIResponse.returnSuccess(order);
    }


    //会员卡扣钱
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void saleGoodsMemberCardOp(ReqPlaceGoodsVo reqPlaceGoodsVo, TbBizPlaceMemberCard tbBizPlaceMemberCard, TbBizPlaceMemberCardType tbBizPlaceMemberCardType, BigDecimal price, String orderNo, String goodsStr) throws java.lang.Exception {
        if (!StringUtils.isEmpty(reqPlaceGoodsVo.getMemberCardId())) {
            BigDecimal initAmount = tbBizPlaceMemberCard.getSurplusAmount();
            BigDecimal initGiveAmount = tbBizPlaceMemberCard.getSurplusGiveAmount();
            BigDecimal zeroAmount = new BigDecimal(0);
            if (tbBizPlaceMemberCard.getCardType() == PlaceConstants.PLACE_MEMBER_CARD_TYPE_VALUE) {//储值卡
                //扣除该会员卡余额  先扣除本金，本金不够再扣除赠送余额，赠送余额不够支付订场失败
                if (!StringUtils.isEmpty(initAmount) && !StringUtils.isEmpty(price)) {
                    //会员卡上的本金大于等于消费金额
                    if (initAmount.doubleValue() >= price.doubleValue()) {
                        tbBizPlaceMemberCard.setSurplusAmount(initAmount.subtract(price));
                    } else {
                        //判断该类型卡的赠送金额是否可以用于买商品
                        if (tbBizPlaceMemberCardType.getGiveAmountIsUse().intValue() == 1) {
                            //会员卡上的本金+赠送金额大于等于消费金额
                            if (initAmount.add(initGiveAmount).doubleValue() >= price.doubleValue()) {
                                BigDecimal surplusGiveAmount = initGiveAmount.subtract(price.subtract(initAmount));
                                tbBizPlaceMemberCard.setSurplusAmount(zeroAmount);
                                tbBizPlaceMemberCard.setSurplusGiveAmount(surplusGiveAmount);
                            } else {
                                throw new java.lang.Exception("请充值会员卡！");
                            }
                        } else {
                            throw new java.lang.Exception("该卡的本金余额不足！请充值！");
                        }
                    }
                }
            } else if (tbBizPlaceMemberCard.getCardType() == PlaceConstants.PLACE_MEMBER_CARD_TYPE_DISCOUNT) {//折扣卡
                //扣除该会员卡余额  先扣除本金，本金不够再扣除赠送余额，赠送余额不够支付订场失败
                if (!StringUtils.isEmpty(initAmount) && !StringUtils.isEmpty(price)) {
                    //会员卡上的本金大于等于消费金额
                    if (initAmount.doubleValue() >= price.doubleValue()) {
                        tbBizPlaceMemberCard.setSurplusAmount(initAmount.subtract(price));
                    }
                    /*else{
                        //会员卡上的本金+赠送金
                        额大于等于消费金额
                        if (tbBizPlaceMemberCard.getSurplusAmount().add(tbBizPlaceMemberCard.getGiveAmount()).doubleValue() >= price.doubleValue()){
                            tbBizPlaceMemberCard.setSurplusAmount(new BigDecimal(0));
                            tbBizPlaceMemberCard.setSurplusGiveAmount(tbBizPlaceMemberCard.getSurplusGiveAmount().subtract(price.subtract(tbBizPlaceMemberCard.getSurplusAmount())));
                        }else{
                            return APIResponse.returnFail("请充值会员卡！");
                        }
                    }*/
                    else {
                        throw new java.lang.Exception("请充值会员卡！");
                    }
                }
            } else if (tbBizPlaceMemberCard.getCardType() == PlaceConstants.PLACE_MEMBER_CARD_TYPE_VALUE_DISCOUNT) {//储值折扣卡
                //扣除该会员卡余额  先扣除本金，本金不够再扣除赠送余额，赠送余额不够支付订场失败
                if (!StringUtils.isEmpty(initAmount) && !StringUtils.isEmpty(price)) {
                    //会员卡上的本金大于等于消费金额
                    if (initAmount.doubleValue() >= price.doubleValue()) {
                        tbBizPlaceMemberCard.setSurplusAmount(tbBizPlaceMemberCard.getSurplusAmount().subtract(price));
                    } else {
                        //判断该类型卡的赠送金额是否可以用于买商品
                        if (tbBizPlaceMemberCardType.getGiveAmountIsUse().intValue() == 1) {
                            //会员卡上的本金+赠送金额大于等于消费金额
                            if (initAmount.add(initGiveAmount).doubleValue() >= price.doubleValue()) {
                                BigDecimal surplusGiveAmount = initGiveAmount.subtract(price.subtract(initAmount));
                                tbBizPlaceMemberCard.setSurplusAmount(zeroAmount);
                                tbBizPlaceMemberCard.setSurplusGiveAmount(surplusGiveAmount);
                            } else {
                                throw new java.lang.Exception("请充值会员卡！");
                            }
                        } else {
                            throw new java.lang.Exception("该卡的本金余额不足！请充值！");
                        }

                    }
                }
            }
            tbBizPlaceMemberCard.setUpdateTime(new Date());
            int flag1 = tbBizPlaceMemberCardMapper.updateByPrimaryKey(tbBizPlaceMemberCard);
            if (flag1 == 1) {
                logger.debug("-------------------会员开单会员卡余额更新完毕-------------");
                //Todo 打折日志记录    折扣前会员价，折扣后价格
                TbBizPlaceMemberOpHistory tbBizPlaceMemberOpHistory = new TbBizPlaceMemberOpHistory();
                tbBizPlaceMemberOpHistory.setCreateUid(reqPlaceGoodsVo.getUid());
                tbBizPlaceMemberOpHistory.setPlaceId(reqPlaceGoodsVo.getPlaceId());
                tbBizPlaceMemberOpHistory.setUpdateTime(new Date());
                tbBizPlaceMemberOpHistory.setAmount(price);
                tbBizPlaceMemberOpHistory.setPayType(reqPlaceGoodsVo.getAdminPayType());
                tbBizPlaceMemberOpHistory.setAdminPayType(PayTypeEnum.getEnum(reqPlaceGoodsVo.getAdminPayType()).getUnifiedId());
                tbBizPlaceMemberOpHistory.setPlatform(PlatformTypeEnum.BACKSTAGE.getId());
                tbBizPlaceMemberOpHistory.setCreateTime(new Date());
                tbBizPlaceMemberOpHistory.setInnerCardNo(tbBizPlaceMemberCard.getInnerCardNo());
                //TODO 生成流水号
                tbBizPlaceMemberOpHistory.setNo(CommonUtils.generateNo(reqPlaceGoodsVo.getPlaceId()));
                tbBizPlaceMemberOpHistory.setOrderNo(orderNo);
                tbBizPlaceMemberOpHistory.setOpTypeName("商家端-商品消费");
                if (!StringUtils.isEmpty(reqPlaceGoodsVo.getMobile())) {
                    Integer uid = placeMemberService.getUidByNameAndPhone(null, reqPlaceGoodsVo.getMobile());
                    tbBizPlaceMemberOpHistory.setUid(uid);
                }
                tbBizPlaceMemberOpHistory.setUserName(reqPlaceGoodsVo.getName());
                tbBizPlaceMemberOpHistory.setMobile(reqPlaceGoodsVo.getMobile());
                TbBizPlaceMemberCard tbBizPlaceMemberCard1 = tbBizPlaceMemberCardMapper.selectByPrimaryKey(reqPlaceGoodsVo.getMemberCardId());
                tbBizPlaceMemberOpHistory.setCardTypeName(tbBizPlaceMemberCard1.getCardName());
                tbBizPlaceMemberOpHistory.setMemo(goodsStr);
                tbBizPlaceMemberOpHistory.setOpAfterAmount(tbBizPlaceMemberCard.getSurplusAmount());
                tbBizPlaceMemberOpHistory.setOpAfterGiveAmount(tbBizPlaceMemberCard.getSurplusGiveAmount());
                tbBizPlaceMemberOpHistory.setState(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_YES);
                tbBizPlaceMemberOpHistory.setOpBeforeAmount(initAmount);
                tbBizPlaceMemberOpHistory.setOpBeforeGiveAmount(initGiveAmount);
                tbBizPlaceMemberOpHistory.setSourceType(PlaceConstants.SOURCE_TYPE_SCENEPAY);
                tbBizPlaceMemberOpHistory.setSrc(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_CONSUMER);
                tbBizPlaceMemberOpHistory.setType(PlaceConstants.PLACE_MEMBER_HISTORY_TYPE_CONSUMER);
                tbBizPlaceMemberOpHistory.setCardTypeId(tbBizPlaceMemberCard1.getCardTypeId());
                int flag2 = tbBizPlaceMemberOpHistoryMapper.insertSelective(tbBizPlaceMemberOpHistory);
                if (flag2 == 1) {
                    logger.debug("-------------------会员开单操作记录完毕-------------");
                }
            }
            TbBizPlace place = placeBaseService.getPlaceById(reqPlaceGoodsVo.getPlaceId());
            List<String> mobileList = new ArrayList<>();
            List<String> paramList = new ArrayList<>();

            //成功消费发送短信提醒
            String[] args = new String[7];
            args[0] = place != null ? place.getName() : "";
            args[1] = tbBizPlaceMemberCard != null ? tbBizPlaceMemberCard.getCardName() : "";
            args[2] = DateUtils.getCurrentTime();
            args[3] = "购买商品";
            args[4] = price != null ? price.toString() + "元" : "";
            args[5] = tbBizPlaceMemberCard != null ? tbBizPlaceMemberCard.getSurplusAmount().add(tbBizPlaceMemberCard.getSurplusGiveAmount()).toString() + "元" : "";
            // 联系电话优先取订场咨询电话，订场电话为空时，取客服电话
            TbBizPlaceAttach placeAttach = placeBaseService.getBizPlaceAttach(reqPlaceGoodsVo.getPlaceId());
            if (null != placeAttach && org.apache.commons.lang3.StringUtils.isNotEmpty(placeAttach.getBookingConsultPhone())) {
                args[6] = placeAttach.getBookingConsultPhone();
            } else {
                // 获取系统配置的百灵鸟客服热线
                TbCommonParameter parameterVo = baseService.getParameterByKey(SysParameterConfigEnum.CONFIG_APP_SERVICE_MOBILE.getCode());
                args[6] = parameterVo != null ? parameterVo.getParameterValue() : "";
            }
            mobileList.add(reqPlaceGoodsVo.getMobile());
            paramList.addAll(Arrays.asList(args));
            try {
                //placeTicketService.asyncSendSms(reqPlaceGoodsVo.getMobile(), SmsApi.MESSAGE_TEMPLATE_PLACE_MEMBER_CONSUME_NOTICE, args, true);
                placeSmsService.sendSms(mobileList, SmsApi.MESSAGE_TEMPLATE_PLACE_MEMBER_CONSUME_NOTICE, PlaceConstants.PLACE_SMS_TYPE_MESSAGE, paramList);
            } catch (java.lang.Exception e) {
                logger.info("短信发送失败-------->" + e.getMessage());
            }
        }
    }

    //商品收入统计
    public RespPlaceGoodsVo goodsSaleIncomeReport(ReqPlaceGoodsVo reqPlaceGoodsVo) {
        /**按商品类别统计
         */
/*        RespPlaceGoodsVo maxVo=new RespPlaceGoodsVo();
        ReqPlaceGoodsTypeVo typeVo=new ReqPlaceGoodsTypeVo();
        typeVo.setPlaceId(reqPlaceGoodsVo.getPlaceId());
        //商品类别
        List<TbBizPlaceGoodsType> typeList=this.getPlaceGoodsTypeData(typeVo);
        List<Integer> ids=new ArrayList<>();
        for (TbBizPlaceGoodsType type :typeList){
            ids.add(type.getId());
        }
        ReqPlaceGoodsVo reqGoodsVo =new ReqPlaceGoodsVo();
        reqGoodsVo.setPlaceId(reqPlaceGoodsVo.getPlaceId());
        reqGoodsVo.setListType(ids);
        //如果商品类别为空，返回，不再做查询
        if (ids.size()==0){
            return  maxVo;
        }
        //获取销售价格按类别区分
         List<RespPlaceGoodsVo> listVal=vPlaceGoodsMapper.goodsSaleIncomeReport(ids,reqPlaceGoodsVo.getPlaceId(),reqPlaceGoodsVo.getStartTime(),reqPlaceGoodsVo.getEndTime());
        for (RespPlaceGoodsVo resp:listVal){
            resp.setPrice(resp.getDebit().multiply(new BigDecimal(resp.getGoodsCount())).setScale(2,BigDecimal.ROUND_HALF_UP));//算出每一个订单的价格
        }
        List<RespPlaceGoodsVo> listTypePrice=new ArrayList<>();
        BigDecimal totalPrice =new BigDecimal(0);
        BigDecimal price =new BigDecimal(0);
        if (ids!=null) {
            for (Integer i : ids) {
                RespPlaceGoodsVo vo = new RespPlaceGoodsVo();
                for (RespPlaceGoodsVo resp : listVal) {
                    if (i.equals(resp.getType())) {
                        price = price.add(resp.getPrice());//算出同类型的订单总价
                    }
                }
                vo.setType(i);
                TbBizPlaceGoodsType voType = this.getGoodsTypeNameByTypeId(i, reqPlaceGoodsVo.getPlaceId());
                if (voType != null) {
                    vo.setTypeName(voType.getName());
                }
                vo.setDebit(price);
                listTypePrice.add(vo);
                totalPrice = totalPrice.add(price);//总销售价
                price = new BigDecimal(0);
            }
            maxVo.setList(listTypePrice);
            maxVo.setDebit(totalPrice);
            logger.info("maxVO-------》" + JSON.toJSONString(maxVo));
            //算百分比：
            NumberFormat percent = NumberFormat.getPercentInstance();//建立百分比格式
            percent.setMaximumFractionDigits(2);
            for (RespPlaceGoodsVo resp : maxVo.getList()) {
                BigDecimal value = new BigDecimal(0);
                String result = "0%";
                int r = totalPrice.compareTo(BigDecimal.ZERO);
                if (!(r == 0)) {
                    value = resp.getDebit().divide(totalPrice, 4, BigDecimal.ROUND_HALF_EVEN);
                    result = percent.format(resp.getDebit().divide(totalPrice, 4, BigDecimal.ROUND_HALF_EVEN));
                }
                resp.setValue(value);
                resp.setPercent(result);
            }
        }
        return  maxVo;*/

        /**
         * 按商品名称统计
         */
        RespPlaceGoodsVo maxVo = new RespPlaceGoodsVo();
        List<RespPlaceGoodsVo> listVal = vPlaceGoodsMapper.goodsSaleIncomeReport(reqPlaceGoodsVo.getPlaceId(), reqPlaceGoodsVo.getStartTime(), reqPlaceGoodsVo.getEndTime());
        for (RespPlaceGoodsVo resp : listVal) {
            resp.setDebit(resp.getDebit().multiply(new BigDecimal(resp.getGoodsCount())).setScale(2, BigDecimal.ROUND_HALF_UP));//算出每一个订单的价格
        }
        //购物车订单
        List<RespPlaceGoodsVo> cartList = vPlaceGoodsMapper.goodsSaleIncomeCartReport(reqPlaceGoodsVo.getPlaceId(), reqPlaceGoodsVo.getStartTime(), reqPlaceGoodsVo.getEndTime());
        listVal.addAll(cartList);
        List<RespPlaceGoodsVo> list = new ArrayList<>();
        BigDecimal totalPrice = new BigDecimal(0);
        int totalGoodsCount = 0;
        BigDecimal price = new BigDecimal(0);
        Map<Integer, RespPlaceGoodsVo> map = new HashMap<Integer, RespPlaceGoodsVo>();
        for (RespPlaceGoodsVo resp : listVal) {
            RespPlaceGoodsVo vos = new RespPlaceGoodsVo();
            if (map.containsKey(resp.getId())) {
                vos.setName(resp.getName());
                vos.setDebit(map.get(resp.getId()).getDebit().add(resp.getDebit()));
                vos.setGoodsCount(map.get(resp.getId()).getGoodsCount().intValue() + resp.getGoodsCount().intValue());
                map.put(resp.getId(), vos);
            } else {
                vos.setName(resp.getName());//商品名称
                vos.setDebit(resp.getDebit());//销售金额
                vos.setGoodsCount(resp.getGoodsCount());//销售数量
                map.put(resp.getId(), vos);
            }
        }

        for (Map.Entry<Integer, RespPlaceGoodsVo> entry : map.entrySet()) {
            RespPlaceGoodsVo vo = new RespPlaceGoodsVo();
            totalPrice = totalPrice.add(entry.getValue().getDebit());
            totalGoodsCount = totalGoodsCount + entry.getValue().getGoodsCount().intValue();
            vo.setId(entry.getKey());
            vo.setDebit(entry.getValue().getDebit());
            vo.setName(entry.getValue().getName());
            vo.setGoodsCount(entry.getValue().getGoodsCount());
            list.add(vo);
        }

        //算百分比：
        NumberFormat percent = NumberFormat.getPercentInstance();//建立百分比格式
        percent.setMaximumFractionDigits(2);
        for (RespPlaceGoodsVo resp : list) {
            BigDecimal value = new BigDecimal(0);
            String result = "0%";
            int r = totalPrice.compareTo(BigDecimal.ZERO);
            if (!(r == 0)) {
                value = resp.getDebit().divide(totalPrice, 4, BigDecimal.ROUND_HALF_EVEN);
                result = percent.format(resp.getDebit().divide(totalPrice, 4, BigDecimal.ROUND_HALF_EVEN));
            }
            resp.setValue(value);
            resp.setPercent(result);
        }
        //按商品销售金额大小降序排序（冒泡排序）
        for (int i = 0; i < list.size(); i++) {
            // 从第i+1为开始循环数组
            for (int j = i + 1; j < list.size(); j++) {
                // 如果前一位比后一位小，那么就将两个数字调换
                // 这里是按降序排列
                // 如果你想按升序排列只要改变K==1
                int k = list.get(i).getDebit().compareTo(list.get(j).getDebit());
                if (k == -1) {
                    RespPlaceGoodsVo tem = list.get(i);
                    list.set(i, list.get(j));
                    list.set(j, tem);
                }
            }
        }
        maxVo.setList(list);
        maxVo.setDebit(totalPrice);
        maxVo.setGoodsCount(totalGoodsCount);
        return maxVo;
    }

    @Override
    public TbBizPlaceGoods getGoodsInfoByid(ReqPlaceGoodsVo reqPlaceGoodsVo) {
        return tbBizPlaceGoodsMapper.selectByPrimaryKey(reqPlaceGoodsVo.getId());
    }


    /**
     * 商品减库存
     *
     * @param tbBizPlaceOrderItemList
     */
    @Override
    public void updateGoodsInventory(List<TbBizPlaceOrderItem> tbBizPlaceOrderItemList, TbBizPlaceOrder tbBizPlaceOrder) {
        if (CollectionUtils.isEmpty(tbBizPlaceOrderItemList)) {
            return;
        }
        for (TbBizPlaceOrderItem tbBizPlaceOrderItem : tbBizPlaceOrderItemList) {
            //// TODO: 2016/11/24 :是否要行锁？
            TbBizPlaceGoods goodsVo = tbBizPlaceGoodsMapper.selectByPrimaryKey(tbBizPlaceOrderItem.getUnitSalePlanId());
            int initInventory = goodsVo.getInventory().intValue();
            int counts = initInventory - tbBizPlaceOrderItem.getTicketCount().intValue();
            TbBizPlaceGoods vo = new TbBizPlaceGoods();
            vo.setId(tbBizPlaceOrderItem.getUnitSalePlanId());
            vo.setInventory(counts);
            tbBizPlaceGoodsMapper.updateByPrimaryKeySelective(vo);

            ReqPlaceGoodsVo reqPlaceGoodsVo = new ReqPlaceGoodsVo();
            reqPlaceGoodsVo.setPlaceId(tbBizPlaceOrder.getPlaceId());
            reqPlaceGoodsVo.setGoodsId(goodsVo.getGoodsId());
            reqPlaceGoodsVo.setPlaceOrderId(tbBizPlaceOrderItem.getPlaceOrderId());
            reqPlaceGoodsVo.setOperateCount(tbBizPlaceOrderItem.getTotalGoodsCount().intValue());
            reqPlaceGoodsVo.setOpBeforeCount(initInventory);
            reqPlaceGoodsVo.setOpAfterCount(counts);
            reqPlaceGoodsVo.setOperateType(1);//售出
            reqPlaceGoodsVo.setUid(tbBizPlaceOrder.getCreateUid());
            reqPlaceGoodsVo.setRemark(tbBizPlaceOrder.getDescrible());
            reqPlaceGoodsVo.setInputTime(new Date());
            insertGoodsOperateRecord(reqPlaceGoodsVo);
        }
    }

    /**
     * 加商品库存 (退款)
     *
     * @param tbBizPlaceOrder
     * @param tbBizPlaceOrderItemList
     * @throws Exception
     */
    public void addGoodsInventory(TbBizPlaceOrder tbBizPlaceOrder, List<TbBizPlaceOrderItem> tbBizPlaceOrderItemList) throws Exception {
        for (TbBizPlaceOrderItem tbBizPlaceOrderItem : tbBizPlaceOrderItemList) {
            TbBizPlaceGoodsExample tbBizPlaceGoodsExample = new TbBizPlaceGoodsExample();
            TbBizPlaceGoodsExample.Criteria tbBizPlaceGoodsExampleCriteria = tbBizPlaceGoodsExample.createCriteria();
            tbBizPlaceGoodsExampleCriteria.andIdEqualTo(tbBizPlaceOrderItem.getUnitSalePlanId());
            tbBizPlaceGoodsExampleCriteria.andPlaceIdEqualTo(tbBizPlaceOrder.getPlaceId());
            List<TbBizPlaceGoods> tbBizPlaceGoodsList = tbBizPlaceGoodsMapper.selectByExample(tbBizPlaceGoodsExample);
            TbBizPlaceGoods goodsVo = tbBizPlaceGoodsList.get(0);
            int initInventory = goodsVo.getInventory().intValue();
            int count = goodsVo.getInventory().intValue() + tbBizPlaceOrderItem.getTicketCount().intValue();
            TbBizPlaceGoods vo = new TbBizPlaceGoods();
            vo.setId(goodsVo.getId());
            vo.setInventory(count);
            int flag1 = tbBizPlaceGoodsMapper.updateByPrimaryKeySelective(vo);
            if (flag1 != 1) {
                throw new Exception("库存更新异常");
            }

            ReqPlaceGoodsVo reqPlaceGoodsVo = new ReqPlaceGoodsVo();
            reqPlaceGoodsVo.setPlaceId(tbBizPlaceOrder.getPlaceId());
            reqPlaceGoodsVo.setGoodsId(goodsVo.getGoodsId());
            reqPlaceGoodsVo.setPlaceOrderId(tbBizPlaceOrderItem.getPlaceOrderId());
            reqPlaceGoodsVo.setOperateCount(tbBizPlaceOrderItem.getTotalGoodsCount().intValue());
            reqPlaceGoodsVo.setOpBeforeCount(initInventory);
            reqPlaceGoodsVo.setOpAfterCount(count);
            reqPlaceGoodsVo.setOperateType(4);//售出
            reqPlaceGoodsVo.setUid(tbBizPlaceOrder.getCreateUid());
            reqPlaceGoodsVo.setRemark(tbBizPlaceOrder.getDescrible());
            reqPlaceGoodsVo.setInputTime(new Date());
            insertGoodsOperateRecord(reqPlaceGoodsVo);
        }
    }

    /**
     * 加商品库存 (部分退款)
     *
     * @param tbBizPlaceOrder //     * @param tbBizPlaceOrderItemList
     * @throws Exception
     */

    @Override
    public void addGoodsInventoryByPart(TbBizPlaceOrder tbBizPlaceOrder, TbBizPlaceOrderItem tbBizPlaceOrderItem,
                                        Integer refundGoodsCount) throws Exception {

        TbBizPlaceGoodsExample tbBizPlaceGoodsExample = new TbBizPlaceGoodsExample();
        TbBizPlaceGoodsExample.Criteria tbBizPlaceGoodsExampleCriteria = tbBizPlaceGoodsExample.createCriteria();
        tbBizPlaceGoodsExampleCriteria.andIdEqualTo(tbBizPlaceOrderItem.getUnitSalePlanId());
        tbBizPlaceGoodsExampleCriteria.andPlaceIdEqualTo(tbBizPlaceOrder.getPlaceId());
        List<TbBizPlaceGoods> tbBizPlaceGoodsList = tbBizPlaceGoodsMapper.selectByExample(tbBizPlaceGoodsExample);
        TbBizPlaceGoods goodsVo = tbBizPlaceGoodsList.get(0);
        int initInventory = goodsVo.getInventory().intValue();
        int count = goodsVo.getInventory().intValue() + refundGoodsCount.intValue();
        TbBizPlaceGoods vo = new TbBizPlaceGoods();
        vo.setId(goodsVo.getId());
        vo.setInventory(count);
        int flag1 = tbBizPlaceGoodsMapper.updateByPrimaryKeySelective(vo);
        if (flag1 != 1) {
            throw new Exception("库存更新异常");
        }

        ReqPlaceGoodsVo reqPlaceGoodsVo = new ReqPlaceGoodsVo();
        reqPlaceGoodsVo.setPlaceId(tbBizPlaceOrder.getPlaceId());
        reqPlaceGoodsVo.setGoodsId(goodsVo.getGoodsId());
        reqPlaceGoodsVo.setPlaceOrderId(tbBizPlaceOrderItem.getPlaceOrderId());
        reqPlaceGoodsVo.setOperateCount(tbBizPlaceOrderItem.getTotalGoodsCount().intValue());
        reqPlaceGoodsVo.setOpBeforeCount(initInventory);
        reqPlaceGoodsVo.setOpAfterCount(count);
        reqPlaceGoodsVo.setOperateType(4);//售出
        reqPlaceGoodsVo.setUid(tbBizPlaceOrder.getCreateUid());
        reqPlaceGoodsVo.setRemark(tbBizPlaceOrder.getDescrible());
        reqPlaceGoodsVo.setInputTime(new Date());
        insertGoodsOperateRecord(reqPlaceGoodsVo);


    }

    /**
     * 库存录入记录
     *
     * @param reqPlaceGoodsVo
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public APIResponse insertInventoryRecord(ReqPlaceGoodsVo reqPlaceGoodsVo) {
        if (reqPlaceGoodsVo.getGoodsCount() == null) {
            return APIResponse.returnFail("库存数量不能为空！");
        }
        if (reqPlaceGoodsVo.getGoodsCount().equals(0)) {
            return APIResponse.returnFail("入库数量不能为0！");
        }
       /* if (StringUtils.isEmpty(reqPlaceGoodsVo.getGoodsBill())){
            return  APIResponse.returnFail("收货单不能为空！");
        }*/
        String inputInventoryCode = PlaceUtil.getPlaceInventoryCode(PlaceConstants.PLACE_INPUT_INVENTORY_CODE);
        String goodsBill = reqPlaceGoodsVo.getGoodsBill();
        String supplierName = reqPlaceGoodsVo.getSupplierName();
        Integer supplierId = reqPlaceGoodsVo.getSupplierId();
        insertInventoryRecordMethod(reqPlaceGoodsVo,inputInventoryCode,null,goodsBill,supplierName,supplierId);
        return APIResponse.returnSuccess();
    }

    public void insertInventoryRecordMethod(ReqPlaceGoodsVo reqPlaceGoodsVo,String code,String batchRemark,String goodsBill,String supplierName,Integer supplierId){
        int goodsCount = reqPlaceGoodsVo.getGoodsCount();
        BigDecimal costTotalPrice = reqPlaceGoodsVo.getCostTotalPrice();//新入库的成本总价

        BigDecimal nPrice = reqPlaceGoodsVo.getCostPrice();
        TbBizPlaceGoods goodsVo = this.getGoodsByGoodsId(reqPlaceGoodsVo.getGoodsId(), reqPlaceGoodsVo.getPlaceId());
        TbBizPlaceGoodsInfo infoVo = this.getGoodsInfoByGoodsId(reqPlaceGoodsVo.getGoodsId(), reqPlaceGoodsVo.getPlaceId());
        int totalCount = goodsCount + goodsVo.getInventory();
        //库存更改
        if (goodsVo != null) {
            BigDecimal oldCost = goodsVo.getCostPrice().multiply(new BigDecimal(goodsVo.getInventory()));//老库存的成本总价
            BigDecimal totalPrice = oldCost.add(costTotalPrice);

            BigDecimal newPrice = totalPrice.divide(new BigDecimal(totalCount), 2, BigDecimal.ROUND_HALF_EVEN);//新成本单价

            int count = goodsVo.getInventory().intValue() + goodsCount;
            TbBizPlaceGoods goods = new TbBizPlaceGoods();
            goods.setInventory(count);
            goods.setCostPrice(newPrice);

            TbBizPlaceGoodsExample example = new TbBizPlaceGoodsExample();
            TbBizPlaceGoodsExample.Criteria criteria = example.createCriteria();
            criteria.andGoodsIdEqualTo(goodsVo.getGoodsId());
            tbBizPlaceGoodsMapper.updateByExampleSelective(goods, example);

       /* else{//新增商品库存
            TbBizPlaceGoods  goods=new TbBizPlaceGoods();
            goods.setInventory(goodsCount);
            goods.setGoodsId(reqPlaceGoodsVo.getGoodsId());
            goods.setCostPrice(reqPlaceGoodsVo.getCostPrice());
            tbBizPlaceGoodsMapper.insert(goods);
        }*/
            //更新条码
       /* TbBizPlaceGoodsInfo info= this.getGoodsInfoByGoodsId(reqPlaceGoodsVo.getGoodsId(),reqPlaceGoodsVo.getPlaceId());
        if (info!=null){
            if (!reqPlaceGoodsVo.getBarCode().trim().equals(info.getBarCode())){
                TbBizPlaceGoodsInfoExample example = new TbBizPlaceGoodsInfoExample();
                TbBizPlaceGoodsInfoExample.Criteria criteria = example.createCriteria();
                criteria.andGoodsIdEqualTo(reqPlaceGoodsVo.getGoodsId());
                criteria.andPlaceIdEqualTo((reqPlaceGoodsVo.getPlaceId()));

                TbBizPlaceGoodsInfo vo=new TbBizPlaceGoodsInfo();
                vo.setBarCode(reqPlaceGoodsVo.getBarCode().trim());
                tbBizPlaceGoodsInfoMapper.updateByExampleSelective(vo,example);
            }
        }*/
            TbBizPlaceGoodsInputInventory inventory = new TbBizPlaceGoodsInputInventory();
            inventory.setPlaceId(reqPlaceGoodsVo.getPlaceId());
            inventory.setCostTotalPrice(reqPlaceGoodsVo.getCostTotalPrice());
            inventory.setSupplierName(supplierName);
            inventory.setSupplierId(supplierId);
            inventory.setSettleWay(reqPlaceGoodsVo.getSettleWay());
            inventory.setInputTime(reqPlaceGoodsVo.getInputTime());//进货时间
            inventory.setInputOperatorUid(reqPlaceGoodsVo.getUid());
            inventory.setGoodsBill(goodsBill);
            inventory.setRemark(reqPlaceGoodsVo.getRemark());
            inventory.setInputInventoryNum(code);
            inventory.setBatchRemark(batchRemark);
            tbBizPlaceGoodsInputInventoryMapper.insert(inventory);
            //入库明细记录
            TbBizPlaceGoodsInputInventoryDetail detailVo = new TbBizPlaceGoodsInputInventoryDetail();
            detailVo.setInventoryId(inventory.getId());
            detailVo.setGoodsId(reqPlaceGoodsVo.getGoodsId());
            detailVo.setBarCode(reqPlaceGoodsVo.getBarCode());
            detailVo.setCostPrice(nPrice);
            detailVo.setGoodsCount(reqPlaceGoodsVo.getGoodsCount());
            detailVo.setInputOperator(reqPlaceGoodsVo.getUid());
            detailVo.setRemainQuantity(totalCount);//剩余数量
            detailVo.setPullGoodsName(infoVo != null ? infoVo.getGoodsName() : "");
            detailVo.setPullGoodsStandard(infoVo != null ? infoVo.getGoodsStandard() : "");
            tbBizPlaceGoodsInputInventoryDetailMapper.insert(detailVo);

            //录入库存流水记录
            reqPlaceGoodsVo.setOperateType(3);
            reqPlaceGoodsVo.setOpBeforeCount(goodsVo.getInventory());
            reqPlaceGoodsVo.setOpAfterCount(totalCount);
            reqPlaceGoodsVo.setOperateCount(totalCount - goodsVo.getInventory());
            reqPlaceGoodsVo.setInputTime(new Date());
            this.insertGoodsOperateRecord(reqPlaceGoodsVo);
        }
    }

    @Override
    public TbBizPlaceGoods getGoodsByGoodsId(String goodsId, Integer placeId) {
        TbBizPlaceGoodsExample example = new TbBizPlaceGoodsExample();
        TbBizPlaceGoodsExample.Criteria criteria = example.createCriteria();
        criteria.andGoodsIdEqualTo(goodsId);
        criteria.andPlaceIdEqualTo(placeId);
        List<TbBizPlaceGoods> list = tbBizPlaceGoodsMapper.selectByExample(example);
        if (list != null && list.size() > 0) {
            return list.get(0);
        } else {
            return null;
        }
    }

    @Override
    public PageObj<List<RespPlaceGoodsVo>> inventoryRecordList(ReqPlaceGoodsVo reqPlaceGoodsVo) {
        int pageNum = 0;
        int pageSize = 20;
        if (reqPlaceGoodsVo.getPageNum() == null) {
            reqPlaceGoodsVo.setPageNum(pageNum);
        }
        if (reqPlaceGoodsVo.getPageSize() == null) {
            reqPlaceGoodsVo.setPageSize(pageSize);
        }
        int total = vPlaceGoodsMapper.inventoryRecordListCount(reqPlaceGoodsVo);
        Page page = new Page(reqPlaceGoodsVo.getPageNum() * reqPlaceGoodsVo.getPageSize(), reqPlaceGoodsVo.getPageSize(), total);
        reqPlaceGoodsVo.setPage(page);
        List<RespPlaceGoodsVo> list = vPlaceGoodsMapper.inventoryRecordList(reqPlaceGoodsVo);
        for (RespPlaceGoodsVo vo : list) {
            TbAdminUser user = adminUserService.getAdminUser(vo.getInputOperatorUid());
            vo.setInputOperatorName(user != null ? user.getTrueName() : null);
        }
        PageObj<List<RespPlaceGoodsVo>> result = PageObj.create(total, reqPlaceGoodsVo.getPageNum(), reqPlaceGoodsVo.getPageSize(), list);
        return result;
    }

    public TbBizPlaceGoodsInfo getGoodsInfoByGoods(ReqPlaceGoodsVo reqPlaceGoodsVo) {
        TbBizPlaceGoodsInfoExample example = new TbBizPlaceGoodsInfoExample();
        TbBizPlaceGoodsInfoExample.Criteria criteria = example.createCriteria();
        criteria.andPlaceIdEqualTo(reqPlaceGoodsVo.getPlaceId());
        criteria.andGoodsIdEqualTo(reqPlaceGoodsVo.getGoodsId());
        List<TbBizPlaceGoodsInfo> list = tbBizPlaceGoodsInfoMapper.selectByExample(example);
        if (list != null && list.size() > 0) {
            return list.get(0);
        } else {
            return null;
        }
    }

    public List<Dict> getOneLevel(String dataKey) {
        DictExample dictExample = new DictExample();
        DictExample.Criteria dictExampleCriteria = dictExample.createCriteria();
        List<String> list = new ArrayList<>();
        list.add("29");
        dictExampleCriteria.andTagGroupIn(list);
        if (!StringUtils.isEmpty(dataKey)) {
            dictExampleCriteria.andDataKeyEqualTo(dataKey);
        }
        List<Dict> dictList = dictMapper.selectByExample(dictExample);
        return dictList;
    }

    public List<TbBizPlaceGoodsType> getTypeByParenLevel(ReqPlaceGoodsVo reqPlaceGoodsVo) {
        TbBizPlaceGoodsTypeExample example = new TbBizPlaceGoodsTypeExample();
        TbBizPlaceGoodsTypeExample.Criteria criteria = example.createCriteria();
        criteria.andPlaceIdEqualTo(reqPlaceGoodsVo.getPlaceId());
        criteria.andLevelEqualTo(reqPlaceGoodsVo.getOneLevelId());
        criteria.andIsDeleteEqualTo(0);
        List<TbBizPlaceGoodsType> list = tbBizPlaceGoodsTypeMapper.selectByExample(example);
        return list;
    }

    @Override
    public TbBizPlaceGoodsInfo getGoodsInfoByGoodsId(String goodsId, Integer placeId) {

        TbBizPlaceGoodsInfoExample example = new TbBizPlaceGoodsInfoExample();
        TbBizPlaceGoodsInfoExample.Criteria criteria = example.createCriteria();
        if (placeId != null) {
            criteria.andPlaceIdEqualTo(placeId);
        }
        if (!StringUtils.isEmpty(goodsId)) {
            criteria.andGoodsIdEqualTo(goodsId);
        }
        List<TbBizPlaceGoodsInfo> list = tbBizPlaceGoodsInfoMapper.selectByExample(example);
        if (list != null && list.size() > 0) {
            return list.get(0);
        } else {
            return null;
        }
    }

    @Override
    public APIResponse saveSupplierInfo(ReqSupplierVo reqSupplierVo) {
        TbSupplier vo = new TbSupplier();
        if (reqSupplierVo != null) {
            vo.setName(reqSupplierVo.getName());
            vo.setAddress(reqSupplierVo.getAddress());
            vo.setCityId(reqSupplierVo.getCityId());
            TbCity city = tbCityMapper.selectByPrimaryKey(reqSupplierVo.getCityId());
            if (city != null) {
                vo.setProvinceId(city.getProvinceId());
            }
            vo.setIsChain((byte) 0);
            vo.setPhone(reqSupplierVo.getPhone());
            vo.setContact(reqSupplierVo.getContact());
            vo.setComment(reqSupplierVo.getComment());
            vo.setIsDelete((byte) 0);
            vo.setSupplierType(1);
            vo.setCreateTime(new Date());
            tbSupplierMapper.insert(vo);
        } else {
            return APIResponse.returnFail("参数不能为空！");
        }
        return APIResponse.returnSuccess();
    }

    @Override
    public PageObj<List<RespSupplierVo>> getSupplierInfoList(ReqSupplierVo reqSupplierVo) {
        if (StringUtils.isEmpty(reqSupplierVo)) {
            APIResponse.returnFail("参数不能为空！");
        }
        if (reqSupplierVo.getPageNum() == null || reqSupplierVo.getPageSize() == null) {
            APIResponse.returnFail("分页参数不能为空");
        }
        Integer pageNum = reqSupplierVo.getPageNum();
        Integer pageSize = reqSupplierVo.getPageSize();
        TbSupplierExample example = new TbSupplierExample();
        TbSupplierExample.Criteria criteria = example.createCriteria();
        if (!StringUtils.isEmpty(reqSupplierVo.getName())) {
            criteria.andNameEqualTo("%" + reqSupplierVo.getName().trim() + "%");
        }
        if (reqSupplierVo.getCityId() != null) {
            criteria.andCityIdEqualTo(reqSupplierVo.getCityId());
        }
        criteria.andIsDeleteEqualTo((byte) 0);
        criteria.andSupplierTypeEqualTo(1);
        int total = tbSupplierMapper.countByExample(example);
        example.setPage(new Page(pageNum * pageSize, pageSize, total));
        List<TbSupplier> list = tbSupplierMapper.selectByExample(example);
        List<RespSupplierVo> respList = new ArrayList<>();
        for (TbSupplier vo : list) {
            RespSupplierVo resp = new RespSupplierVo();
            resp.setId(vo.getId());
            resp.setAddress(vo.getAddress());
            resp.setName(vo.getName());
            resp.setComment(vo.getComment());
            if (vo.getCityId() != null) {
                TbCity city = tbCityMapper.selectByPrimaryKey(vo.getCityId());
                resp.setCityName(city.getName());
            }
            resp.setContact(vo.getContact());
            resp.setPhone(vo.getPhone());
            respList.add(resp);
        }
        PageObj<List<RespSupplierVo>> result = PageObj.create(total, pageNum, pageSize, respList);
        return result;
    }

    @Override
    public APIResponse deleteSupplierInfo(ReqSupplierVo reqSupplierVo) {
        TbSupplier vo = new TbSupplier();
        vo.setId(reqSupplierVo.getId());
        vo.setIsDelete((byte) 1);
        tbSupplierMapper.updateByPrimaryKeySelective(vo);
        return APIResponse.returnSuccess();
    }

    @Override
    public APIResponse updateSupplierInfo(ReqSupplierVo reqSupplierVo) {
        TbSupplier vo = new TbSupplier();
        vo.setId(reqSupplierVo.getId());
        vo.setAddress(reqSupplierVo.getAddress());
        vo.setContact(reqSupplierVo.getContact());
        vo.setComment(reqSupplierVo.getComment());
        vo.setPhone(reqSupplierVo.getPhone());
        vo.setCityId(reqSupplierVo.getCityId());
        vo.setName(reqSupplierVo.getName());
        tbSupplierMapper.updateByPrimaryKeySelective(vo);
        return APIResponse.returnSuccess();
    }

    @Override
    public List<TbSupplier> getSupplierNameByCityId(Integer cityId) {
        TbSupplierExample example = new TbSupplierExample();
        TbSupplierExample.Criteria criteria = example.createCriteria();
        criteria.andCityIdEqualTo(cityId);
        criteria.andSupplierTypeEqualTo(1);
        criteria.andIsDeleteEqualTo((byte) 0);
        tbSupplierMapper.selectByExample(example);
        List<TbSupplier> list = tbSupplierMapper.selectByExample(example);
        return list;
    }

    /**
     * 库存盘点
     *
     * @param reqPlaceGoodsVo
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public APIResponse checkGoodsInventory(ReqPlaceGoodsVo reqPlaceGoodsVo) {
        if (StringUtils.isEmpty(reqPlaceGoodsVo)) {
            APIResponse.returnFail("参数不能为空");
        }
        String checkInventoryCode = PlaceUtil.getPlaceInventoryCode(PlaceConstants.PLACE_CHECK_INVENTORY_CODE);
        checkGoodsInventoryMethod(reqPlaceGoodsVo,checkInventoryCode,null);
        return APIResponse.returnSuccess();
    }

    public void checkGoodsInventoryMethod(ReqPlaceGoodsVo reqPlaceGoodsVo,String code,String batchRemark){
        //更新库存
        TbBizPlaceGoodsExample example = new TbBizPlaceGoodsExample();
        TbBizPlaceGoodsExample.Criteria criteria = example.createCriteria();
        criteria.andPlaceIdEqualTo(reqPlaceGoodsVo.getPlaceId());
        criteria.andGoodsIdEqualTo(reqPlaceGoodsVo.getGoodsId());
        TbBizPlaceGoods goods = new TbBizPlaceGoods();
        List<TbBizPlaceGoods> list  =tbBizPlaceGoodsMapper.selectByExample(example);
        Integer inventory = null;
        if(list!=null&&list.size()>0){
            inventory = list.get(0).getInventory();
        }else{
            inventory = reqPlaceGoodsVo.getInventory();
        }
        if(reqPlaceGoodsVo.getAfterCheckInventory()!=null) {
            goods.setInventory(reqPlaceGoodsVo.getAfterCheckInventory());
            tbBizPlaceGoodsMapper.updateByExampleSelective(goods, example);
            //盘点库存记录
            TbBizPlaceGoodsCheckRecord vo = new TbBizPlaceGoodsCheckRecord();
            vo.setCheckInventoryNum(code);
            vo.setBatchRemark(batchRemark);
            vo.setGoodsId(reqPlaceGoodsVo.getGoodsId());
            vo.setPlaceId(reqPlaceGoodsVo.getPlaceId());
            vo.setBeforeCheckInventory(inventory);
            vo.setAfterCheckInventory(reqPlaceGoodsVo.getAfterCheckInventory());
            vo.setCheckResult(reqPlaceGoodsVo.getAfterCheckInventory().intValue() - inventory);
            if (vo.getCheckResult().intValue() > 0) {
                vo.setStatus(PlaceConstants.PLACE_GOODS_CHECK_ZERO);
            } else if (vo.getCheckResult().intValue() < 0) {
                vo.setStatus(PlaceConstants.PLACE_GOODS_CHECK_ONE);
            } else if (vo.getCheckResult().intValue() == 0) {
                vo.setStatus(PlaceConstants.PLACE_GOODS_CHECK_TWO);
            }
            vo.setUid(reqPlaceGoodsVo.getUid());
            vo.setRemark(reqPlaceGoodsVo.getRemark());
            tbBizPlaceGoodsCheckRecordMapper.insert(vo);

            //盘点库存流水记录
            reqPlaceGoodsVo.setOperateType(2);
            reqPlaceGoodsVo.setStatus(vo.getStatus());
            reqPlaceGoodsVo.setCheckResult(vo.getCheckResult());
            reqPlaceGoodsVo.setRemark(vo.getRemark());
            reqPlaceGoodsVo.setOpBeforeCount(vo.getBeforeCheckInventory());
            reqPlaceGoodsVo.setOpAfterCount(reqPlaceGoodsVo.getAfterCheckInventory());
            reqPlaceGoodsVo.setOperateCount(vo.getCheckResult());
            reqPlaceGoodsVo.setInputTime(new Date());
            this.insertGoodsOperateRecord(reqPlaceGoodsVo);
        }
    }
    @Override
    public PageObj<List<RespPlaceGoodsVo>> goodsTradeRecord(ReqPlaceGoodsVo reqPlaceGoodsVo) {
        if (StringUtils.isEmpty(reqPlaceGoodsVo)) {
            APIResponse.returnFail("参数不能为空");
        }
        if (StringUtils.isEmpty(reqPlaceGoodsVo.getPlaceOrderId())) {
            reqPlaceGoodsVo.setPlaceOrderId(null);
        } else {
            if (reqPlaceGoodsVo.getPlaceOrderId().trim().length() > 18) {
                reqPlaceGoodsVo.setPlaceOrderId(reqPlaceGoodsVo.getPlaceOrderId().trim());
            } else {
                reqPlaceGoodsVo.setPlaceOrderId("%" + reqPlaceGoodsVo.getPlaceOrderId().trim() + "%");
            }
        }
        if (StringUtils.isEmpty(reqPlaceGoodsVo.getsTime())) {
            reqPlaceGoodsVo.setsTime(null);
        }
        if (StringUtils.isEmpty(reqPlaceGoodsVo.geteTime())) {
            reqPlaceGoodsVo.seteTime(null);
        }
        Integer pageNum = reqPlaceGoodsVo.getPageNum();
        Integer pageSize = reqPlaceGoodsVo.getPageSize();
        PageObj<List<RespPlaceGoodsVo>> resList = null;
        List<RespPlaceGoodsVo> list = null;
        int total = 0;
        //1: '销售',2:'盘盈',3:'盘亏',4:'盘平',5:'入库',6:'退款'
        /*
        if ("1".equals(reqPlaceGoodsVo.getFlag().toString())){
            total=vPlaceGoodsMapper.getGoodsOrdersDataCount(reqPlaceGoodsVo);
            Page page = new Page(pageNum * pageSize, pageSize,total);
            reqPlaceGoodsVo.setPage(page);
            list=vPlaceGoodsMapper.getGoodsOrdersData(reqPlaceGoodsVo);
            for (RespPlaceGoodsVo vo:list){
                if (vo.getUid()!=null){
                   TbAdminUser user= adminUserService.getAdminUser(vo.getUid());
                    vo.setOperatorName(user!=null?user.getTrueName():"");
                }
            }
             resList = PageObj.create(total, pageNum, pageSize, list);
        }
        if ("2".equals(reqPlaceGoodsVo.getFlag().toString())||"3".equals(reqPlaceGoodsVo.getFlag().toString())||"4".equals(reqPlaceGoodsVo.getFlag().toString())){
            total=vPlaceGoodsMapper.getGoodsCheckDataCount(reqPlaceGoodsVo);
            Page page = new Page(pageNum * pageSize, pageSize,total);
            reqPlaceGoodsVo.setPage(page);
            if ("2".equals(reqPlaceGoodsVo.getFlag().toString())){
                reqPlaceGoodsVo.setStatus(PlaceConstants.PLACE_GOODS_CHECK_ZERO);
            }else if ("3".equals(reqPlaceGoodsVo.getFlag().toString())){
                reqPlaceGoodsVo.setStatus(PlaceConstants.PLACE_GOODS_CHECK_ONE);
            }else if ("4".equals(reqPlaceGoodsVo.getFlag().toString())){
                reqPlaceGoodsVo.setStatus(PlaceConstants.PLACE_GOODS_CHECK_TWO);
            }
            list=vPlaceGoodsMapper.getGoodsCheckData(reqPlaceGoodsVo);
            for (RespPlaceGoodsVo vo:list){
                if (vo.getUid()!=null){
                    TbAdminUser user= adminUserService.getAdminUser(vo.getUid());
                    vo.setOperatorName(user!=null?user.getTrueName():"");
                }
            }
            resList = PageObj.create(total, pageNum, pageSize, list);
        }
        if ("5".equals(reqPlaceGoodsVo.getFlag().toString())){
            total=vPlaceGoodsMapper.getGoodsInventoryDataCount(reqPlaceGoodsVo);
            Page page = new Page(pageNum * pageSize, pageSize,total);
            reqPlaceGoodsVo.setPage(page);
            list=vPlaceGoodsMapper.getGoodsInventoryData(reqPlaceGoodsVo);
            for (RespPlaceGoodsVo vo:list){
                if (vo.getUid()!=null){
                    TbAdminUser user= adminUserService.getAdminUser(vo.getUid());
                    vo.setOperatorName(user!=null?user.getTrueName():"");
                }
            }
            resList = PageObj.create(total, pageNum, pageSize, list);
        }
        if ("6".equals(reqPlaceGoodsVo.getFlag().toString())){
            total=vPlaceGoodsMapper.getGoodsRefundOrdersDataCount(reqPlaceGoodsVo);
            Page page = new Page(pageNum * pageSize, pageSize,total);
            reqPlaceGoodsVo.setPage(page);
            list=vPlaceGoodsMapper.getGoodsRefundOrdersData(reqPlaceGoodsVo);
            for (RespPlaceGoodsVo vo:list){
                if (vo.getUid()!=null){
                    TbAdminUser user= adminUserService.getAdminUser(vo.getUid());
                    vo.setOperatorName(user!=null?user.getTrueName():"");
                }
            }
            resList = PageObj.create(total, pageNum, pageSize, list);
        }
        */
        //0:全部,1: '销售',2:'盘盈',3:'盘亏',4:'盘平',5:'入库',6:'退款',7:'赠送'
        if (PlaceConstants.PLACE_GOODS_HISTORY_ZERO.equals(reqPlaceGoodsVo.getFlag())) {
            reqPlaceGoodsVo.setOperateType(null);
        } else if (PlaceConstants.PLACE_GOODS_HISTORY_ONE.equals(reqPlaceGoodsVo.getFlag())) {
            reqPlaceGoodsVo.setOperateType(1);
        } else if (PlaceConstants.PLACE_GOODS_HISTORY_TWO.equals(reqPlaceGoodsVo.getFlag())) {
            reqPlaceGoodsVo.setOperateType(2);
            reqPlaceGoodsVo.setStatus(0);
        } else if (PlaceConstants.PLACE_GOODS_HISTORY_THREE.equals(reqPlaceGoodsVo.getFlag())) {
            reqPlaceGoodsVo.setOperateType(2);
            reqPlaceGoodsVo.setStatus(1);
        } else if (PlaceConstants.PLACE_GOODS_HISTORY_FOUR.equals(reqPlaceGoodsVo.getFlag())) {
            reqPlaceGoodsVo.setOperateType(2);
            reqPlaceGoodsVo.setStatus(2);
        } else if (PlaceConstants.PLACE_GOODS_HISTORY_FIVE.equals(reqPlaceGoodsVo.getFlag())) {
            reqPlaceGoodsVo.setOperateType(3);
        } else if (PlaceConstants.PLACE_GOODS_HISTORY_SIX.equals(reqPlaceGoodsVo.getFlag())) {
            reqPlaceGoodsVo.setOperateType(4);
        } else if (PlaceConstants.PLACE_GOODS_HISTORY_SEVEN.equals(reqPlaceGoodsVo.getFlag())) {
            reqPlaceGoodsVo.setOperateType(5);
        }
        total = vPlaceGoodsMapper.getGoodsInventoryHistroyCount(reqPlaceGoodsVo);
        Page page = new Page(pageNum * pageSize, pageSize, total);
        reqPlaceGoodsVo.setPage(page);
        list = vPlaceGoodsMapper.getGoodsInventoryHistroy(reqPlaceGoodsVo);
        for (RespPlaceGoodsVo vo : list) {
            if (vo.getUid() != null) {
                TbAdminUser user = adminUserService.getAdminUser(vo.getUid());
                vo.setOperatorName(user != null ? user.getTrueName() : "");
            }
        }
        resList = PageObj.create(total, pageNum, pageSize, list);
        return resList;
    }

    /**
     * 商品库存操作流水记录
     *
     * @param reqPlaceGoodsVo
     */
    @Override
    public void insertGoodsOperateRecord(ReqPlaceGoodsVo reqPlaceGoodsVo) {
        TbBizPlaceGoodsHistory history = new TbBizPlaceGoodsHistory();
        history.setPlaceId(reqPlaceGoodsVo.getPlaceId());
        history.setGoodsId(reqPlaceGoodsVo.getGoodsId());
        history.setPlaceOrderId(reqPlaceGoodsVo.getPlaceOrderId());
        history.setOperateCount(reqPlaceGoodsVo.getOperateCount());
        history.setOpBeforeCount(reqPlaceGoodsVo.getOpBeforeCount());
        history.setOpAfterCount(reqPlaceGoodsVo.getOpAfterCount());
        history.setOperateType(reqPlaceGoodsVo.getOperateType());
        history.setCheckResult(reqPlaceGoodsVo.getCheckResult());
        history.setStatus(reqPlaceGoodsVo.getStatus());
        history.setUid(reqPlaceGoodsVo.getUid());
        history.setRemark(reqPlaceGoodsVo.getRemark());
        history.setInputTime(reqPlaceGoodsVo.getInputTime());
        tbBizPlaceGoodsHistoryMapper.insert(history);
    }

    /**
     * 统一商品库（新增商品类型）
     *
     * @param map
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public APIResponse<?> insertGoodsCommonType(@Param("map") Map<String, Object> map) {
        Integer oneLevelId = MapUtils.getInteger(map, "oneLevelId");
        String twoLevelName = MapUtils.getString(map, "twoLevelName").trim();
        if (oneLevelId == null) {
            return APIResponse.returnFail("一级类别不能为空！");
        }
        if (StringUtils.isEmpty(twoLevelName)) {
            return APIResponse.returnFail("二级类别不能为空");
        }
        TbBizPlaceGoodsTypeCommonExample example = new TbBizPlaceGoodsTypeCommonExample();
        TbBizPlaceGoodsTypeCommonExample.Criteria criteria = example.createCriteria();
        criteria.andNameEqualTo(twoLevelName.trim());
        List<TbBizPlaceGoodsTypeCommon> tbBizPlaceGoodsTypeCommons = tbBizPlaceGoodsTypeCommonMapper.selectByExample(example);
        if (tbBizPlaceGoodsTypeCommons != null && tbBizPlaceGoodsTypeCommons.size() > 0) {
            return APIResponse.returnFail("该商品类型名称已存在!");
        }
        TbBizPlaceGoodsTypeCommon tbBizPlaceGoodsTypeCommon = new TbBizPlaceGoodsTypeCommon();
        tbBizPlaceGoodsTypeCommon.setLevel(oneLevelId);
        tbBizPlaceGoodsTypeCommon.setName(twoLevelName);
        tbBizPlaceGoodsTypeCommon.setIsDelete(0);
        tbBizPlaceGoodsTypeCommonMapper.insertSelective(tbBizPlaceGoodsTypeCommon);
        return APIResponse.returnSuccess("新增统一商品类型成功");
    }

    /**
     * 统一商品库（更新商品类型）
     *
     * @param map
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public APIResponse<?> updateGoodsCommonType(@Param("map") Map<String, Object> map) {
        Integer oneLevelId = MapUtils.getInteger(map, "oneLevelId");
        String twoLevelName = MapUtils.getString(map, "twoLevelName");
        Integer id = MapUtils.getInteger(map, "id");
        if (oneLevelId == null) {
            return APIResponse.returnFail("一级类别不能为空！");
        }
        if (StringUtils.isEmpty(twoLevelName)) {
            return APIResponse.returnFail("二级类别不能为空");
        }
        if (id == null) {
            return APIResponse.returnFail("无法获取刚商品类型！");
        }
        TbBizPlaceGoodsTypeCommon oldGoodsType = tbBizPlaceGoodsTypeCommonMapper.selectByPrimaryKey(id);

            if(!oldGoodsType.getName().equals(twoLevelName)){
                if(oldGoodsType.getLevel()!=oneLevelId){
                    TbBizPlaceGoodsTypeCommonExample example = new TbBizPlaceGoodsTypeCommonExample();
                    TbBizPlaceGoodsTypeCommonExample.Criteria criteria = example.createCriteria();
                    criteria.andNameEqualTo(twoLevelName.trim());
                    List<TbBizPlaceGoodsTypeCommon> tbBizPlaceGoodsTypeCommons = tbBizPlaceGoodsTypeCommonMapper.selectByExample(example);
                    if (tbBizPlaceGoodsTypeCommons != null && tbBizPlaceGoodsTypeCommons.size() > 0) {
                        return APIResponse.returnFail("该商品类型名称已存在!");
                }
            }
        }
        TbBizPlaceGoodsTypeCommon tbBizPlaceGoodsTypeCommon = new TbBizPlaceGoodsTypeCommon();
        tbBizPlaceGoodsTypeCommon.setLevel(oneLevelId);
        tbBizPlaceGoodsTypeCommon.setName(twoLevelName);
        tbBizPlaceGoodsTypeCommon.setId(id);
        tbBizPlaceGoodsTypeCommon.setUpdateTime(new Date());
        tbBizPlaceGoodsTypeCommonMapper.updateByPrimaryKeySelective(tbBizPlaceGoodsTypeCommon);
        //一级类型修改时，要去修改商品对应的一级类型
        if(oldGoodsType.getLevel()!=oneLevelId){
            TbBizPlaceGoodsCommonExample example = new TbBizPlaceGoodsCommonExample();
            example.createCriteria().andTwoLevelTypeIdEqualTo(id);
            List<TbBizPlaceGoodsCommon> list = tbBizPlaceGoodsCommonMapper.selectByExample(example);
            if(list!=null&&list.size()>0){
                for(int i = 0;i < list.size(); i++){
                    TbBizPlaceGoodsCommon goods = list.get(i);
                    goods.setOneLevelTypeId(oneLevelId);
                    tbBizPlaceGoodsCommonMapper.updateByPrimaryKeySelective(goods);
                    //修改商家端商品
                    ReqPlaceGoodsCommonVo reqPlaceGoodsCommonVo = new ReqPlaceGoodsCommonVo();
                    org.springframework.beans.BeanUtils.copyProperties(goods,reqPlaceGoodsCommonVo);
                    reqPlaceGoodsCommonVo.setOneLevelId(goods.getOneLevelTypeId());
                    reqPlaceGoodsCommonVo.setTwoLevelId(goods.getTwoLevelTypeId());
                    goods.setOneLevelTypeId(oldGoodsType.getLevel());
                    goods.setTwoLevelTypeId(oldGoodsType.getId());
                    updateGoodsCommonMethod(reqPlaceGoodsCommonVo,goods);
                }
            }
        }
        return APIResponse.returnSuccess("更新统一商品类型成功");
    }

    /**
     * 统一商品库（商品类型列表）
     *
     * @param map
     * @return
     */
    public APIResponse<?> goodsTypeCommonList(@Param("map") Map<String, Object> map) {
        Integer pageNum = Constants.DEFAULT_PAGE_NUM;
        Integer pageSize = Constants.DEFAULT_PAGE_SIZE;
        Integer reqPageNum = MapUtils.getInteger(map, "pageNum");
        if (!StringUtils.isEmpty(MapUtils.getInteger(map, "pageSize"))) {
            pageSize = MapUtils.getInteger(map, "pageSize");
        }
        if (!StringUtils.isEmpty(MapUtils.getInteger(map, "pageNum"))) {
            pageNum = MapUtils.getInteger(map, "pageNum") * pageSize;
        }
        map.put("pageNum", pageNum);
        map.put("pageSize", pageSize);
        Integer total = vPlaceGoodsMapper.countCoodsTypeCommonList(map);
        List<TbBizPlaceGoodsTypeCommon> list = vPlaceGoodsMapper.getGoodsTypeCommonList(map);
        PageObj<List<TbBizPlaceGoodsTypeCommon>> result = PageObj.create(total, reqPageNum, pageSize, list);

        return APIResponse.returnSuccess(result);
    }

    /**
     * 统一商品库信息（新增商品）
     *
     * @param reqPlaceGoodsCommonVo
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public APIResponse<?> insertGoodsCommon(ReqPlaceGoodsCommonVo reqPlaceGoodsCommonVo) {
        if(checkGoodsCommon(reqPlaceGoodsCommonVo)!=null){
            return (checkGoodsCommon(reqPlaceGoodsCommonVo));
        }else{
            if (!StringUtils.isEmpty(reqPlaceGoodsCommonVo.getBarCode())) {
                TbBizPlaceGoodsCommon infoVo = this.checkCommonBarCode(reqPlaceGoodsCommonVo.getBarCode(), null);
                if (infoVo != null) {
                    return APIResponse.returnFail("该商品条码已存在！");
                }
            }
            if (!StringUtils.isEmpty(reqPlaceGoodsCommonVo.getGoodsCode())) {
                TbBizPlaceGoodsCommon infoVo = this.checkCommonGoodsCode(reqPlaceGoodsCommonVo.getGoodsCode(), null);
                if (infoVo != null) {
                    return APIResponse.returnFail("该商品编号已存在！");
                }
            }
            if (!StringUtils.isEmpty(reqPlaceGoodsCommonVo.getGoodsStandard())) {
                TbBizPlaceGoodsCommon infoVo = this.checkCommonGoodsStandard(reqPlaceGoodsCommonVo.getGoodsName(),reqPlaceGoodsCommonVo.getGoodsStandard(), null);
                if (infoVo != null) {
                    return APIResponse.returnFail("有同样商品名称的商品规格不能重复！");
                }
            }
            TbBizPlaceGoodsCommon goods = new TbBizPlaceGoodsCommon();
            goods.setGoodsId(UUIDUtils.getUUID());
            goods.setGoodsCode(reqPlaceGoodsCommonVo.getGoodsCode());
            goods.setGoodsName(reqPlaceGoodsCommonVo.getGoodsName());
            goods.setOneLevelTypeId(reqPlaceGoodsCommonVo.getOneLevelId());
            goods.setTwoLevelTypeId(reqPlaceGoodsCommonVo.getTwoLevelId());
            goods.setBarCode(reqPlaceGoodsCommonVo.getBarCode());
            goods.setGoodsUnit(reqPlaceGoodsCommonVo.getGoodsUnit());
            goods.setGoodsStandard(reqPlaceGoodsCommonVo.getGoodsStandard());
            goods.setGuideOriginPrice(reqPlaceGoodsCommonVo.getGuideOriginPrice());
            goods.setGuideMemberPrice(reqPlaceGoodsCommonVo.getGuideMemberPrice());
            goods.setGuideCostPrice(reqPlaceGoodsCommonVo.getGuideCostPrice());
            goods.setGoodsImgUrl(reqPlaceGoodsCommonVo.getGoodsImgUrl());
            goods.setIsDelete(0);
            goods.setCreateTime(new Date());
            goods.setUpdateTime(goods.getCreateTime());
            tbBizPlaceGoodsCommonMapper.insertSelective(goods);
            return APIResponse.returnSuccess("新增统一商品成功");
        }
    }

    /**
     * 统一商品库信息（更新商品）
     *
     * @param reqPlaceGoodsCommonVo
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public APIResponse<?> updateGoodsCommon(ReqPlaceGoodsCommonVo reqPlaceGoodsCommonVo) {
        if(checkGoodsCommon(reqPlaceGoodsCommonVo)!=null){
            return (checkGoodsCommon(reqPlaceGoodsCommonVo));
        }else{
            if (StringUtils.isEmpty(reqPlaceGoodsCommonVo.getId())) {
                return APIResponse.returnFail("商品id要传");
            }
            TbBizPlaceGoodsCommon oldGoods = tbBizPlaceGoodsCommonMapper.selectByPrimaryKey(reqPlaceGoodsCommonVo.getId());
            if(!oldGoods.getGoodsCode().equals(reqPlaceGoodsCommonVo.getGoodsCode())){
                if (!StringUtils.isEmpty(reqPlaceGoodsCommonVo.getGoodsCode())) {
                    TbBizPlaceGoodsCommon infoVo = this.checkCommonGoodsCode(reqPlaceGoodsCommonVo.getGoodsCode(), null);
                    if (infoVo != null) {
                        return APIResponse.returnFail("该商品编号已存在！");
                    }
                }
            }
            if(!oldGoods.getBarCode().equals(reqPlaceGoodsCommonVo.getBarCode())){
                if (!StringUtils.isEmpty(reqPlaceGoodsCommonVo.getBarCode())) {
                    TbBizPlaceGoodsCommon infoVo = this.checkCommonBarCode(reqPlaceGoodsCommonVo.getBarCode(), null);
                    if (infoVo != null) {
                        return APIResponse.returnFail("该商品条码已存在！");
                    }
                }
            }
            if(!(oldGoods.getGoodsStandard().equals(reqPlaceGoodsCommonVo.getGoodsStandard())&&oldGoods.getGoodsName().equals(reqPlaceGoodsCommonVo.getGoodsName()))) {
                if (!StringUtils.isEmpty(reqPlaceGoodsCommonVo.getGoodsStandard())) {
                    TbBizPlaceGoodsCommon infoVo = this.checkCommonGoodsStandard(reqPlaceGoodsCommonVo.getGoodsName(), reqPlaceGoodsCommonVo.getGoodsStandard(), null);
                    if (infoVo != null) {
                        return APIResponse.returnFail("有同样商品名称的商品规格不能重复！");
                    }
                }
            }
            updateGoodsCommonMethod(reqPlaceGoodsCommonVo,oldGoods);
            return APIResponse.returnSuccess("更新统一商品成功");
        }

    }
    public void updateGoodsCommonMethod(ReqPlaceGoodsCommonVo reqPlaceGoodsCommonVo,TbBizPlaceGoodsCommon oldGoods){
        TbBizPlaceGoodsCommon goods = new TbBizPlaceGoodsCommon();
        goods.setId(reqPlaceGoodsCommonVo.getId());
        goods.setGoodsCode(reqPlaceGoodsCommonVo.getGoodsCode());
        goods.setGoodsName(reqPlaceGoodsCommonVo.getGoodsName());
        goods.setOneLevelTypeId(reqPlaceGoodsCommonVo.getOneLevelId());
        goods.setTwoLevelTypeId(reqPlaceGoodsCommonVo.getTwoLevelId());
        goods.setBarCode(reqPlaceGoodsCommonVo.getBarCode());
        goods.setGoodsUnit(reqPlaceGoodsCommonVo.getGoodsUnit());
        goods.setGoodsStandard(reqPlaceGoodsCommonVo.getGoodsStandard());
        goods.setGuideOriginPrice(reqPlaceGoodsCommonVo.getGuideOriginPrice());
        goods.setGuideMemberPrice(reqPlaceGoodsCommonVo.getGuideMemberPrice());
        goods.setGuideCostPrice(reqPlaceGoodsCommonVo.getGuideCostPrice());
        goods.setGoodsImgUrl(reqPlaceGoodsCommonVo.getGoodsImgUrl());
        goods.setIsDelete(0);
        goods.setUpdateTime(new Date());
        tbBizPlaceGoodsCommonMapper.updateByPrimaryKeySelective(goods);

        //统一商品库信息修改时，要去修改商家端商品对应的信息
        TbBizPlaceGoodsInfoExample example = new TbBizPlaceGoodsInfoExample();
        example.createCriteria().andGoodsCommonIdEqualTo(goods.getId());
        List<TbBizPlaceGoodsInfo> list = tbBizPlaceGoodsInfoMapper.selectByExample(example);
        if(list!=null&&list.size()>0){
            for(int i = 0;i<list.size();i++) {
                TbBizPlaceGoodsInfo info = list.get(i);
                if (!oldGoods.getGoodsCode().equals(goods.getGoodsCode())) {
                    info.setGoodsCode(goods.getGoodsCode());
                }
                if (!oldGoods.getGoodsName().equals(goods.getGoodsName())) {
                    info.setGoodsName(goods.getGoodsName());
                    //更新库存表tb_biz_place_goods的name
                    TbBizPlaceGoodsExample example1 = new TbBizPlaceGoodsExample();
                    example1.createCriteria().andGoodsIdEqualTo(info.getGoodsId());
                    List<TbBizPlaceGoods> list1 = tbBizPlaceGoodsMapper.selectByExample(example1);
                    if (list != null && list.size() > 0) {
                        TbBizPlaceGoods goods1 = list1.get(0);
                        goods1.setName(goods.getGoodsName());
                        tbBizPlaceGoodsMapper.updateByPrimaryKeySelective(goods1);
                    }
                }
                if (!oldGoods.getOneLevelTypeId().equals(goods.getOneLevelTypeId())) {
                    info.setOneLevelTypeId(goods.getOneLevelTypeId());
                }
                if (!oldGoods.getTwoLevelTypeId().equals(goods.getTwoLevelTypeId())) {
                    info.setTwoLevelTypeId(goods.getTwoLevelTypeId());
                }
                if (!oldGoods.getBarCode().equals(goods.getBarCode())) {
                    info.setBarCode(goods.getBarCode());
                }
                if (!oldGoods.getGoodsUnit().equals(goods.getGoodsUnit())) {
                    info.setGoodsUnit(goods.getGoodsUnit());
                }
                if (!oldGoods.getGoodsStandard().equals(goods.getGoodsStandard())) {
                    info.setGoodsStandard(goods.getGoodsStandard());
                }
                if (!oldGoods.getGoodsImgUrl().equals(goods.getGoodsImgUrl())) {
                    info.setGoodsImgUrl(goods.getGoodsImgUrl());
                }
                if (!oldGoods.getIsDelete().equals(goods.getIsDelete())) {
                    info.setIsDelete(goods.getIsDelete());
                }
                tbBizPlaceGoodsInfoMapper.updateByPrimaryKeySelective(info);
            }
        }
    }
    /**
     * 统一商品库信息（商品列表）
     *
     * @param map
     * @return
     */
    public APIResponse<?> goodsCommonList(@Param("map") Map<String, Object> map) {
        Integer pageNum = Constants.DEFAULT_PAGE_NUM;
        Integer pageSize = Constants.DEFAULT_PAGE_SIZE;
        Integer reqPageNum = MapUtils.getInteger(map, "pageNum");
        if (!StringUtils.isEmpty(MapUtils.getInteger(map, "pageSize"))) {
            pageSize = MapUtils.getInteger(map, "pageSize");
        }
        if (!StringUtils.isEmpty(MapUtils.getInteger(map, "pageNum"))) {
            pageNum = MapUtils.getInteger(map, "pageNum") * pageSize;
        }
        map.put("pageNum", pageNum);
        map.put("pageSize", pageSize);
        if(!StringUtils.isEmpty(MapUtils.getInteger(map, "commonFlag"))){
            String flag = MapUtils.getString(map, "commonFlag");
            map.put("commonFlag",flag);
        }
        Integer total = vPlaceGoodsMapper.countCoodsCommonList(map);
        List<RespPlaceGoodsCommonVo> list = vPlaceGoodsMapper.getGoodsCommonList(map);
        for(RespPlaceGoodsCommonVo respPlaceGoodsCommonVo : list){
            String oneId = respPlaceGoodsCommonVo.getOneLevelTypeId()+"";
            String oneName = "";
            List<Dict> listDict = this.getOneLevel(null);
            for(Dict dict : listDict){
                if(oneId.equals(dict.getDataKey())){
                    oneName=dict.getDataValue();
                }
            }
            respPlaceGoodsCommonVo.setOneLevelName(oneName);
        }
        PageObj<List<RespPlaceGoodsCommonVo>> result = PageObj.create(total, reqPageNum, pageSize, list);

        return APIResponse.returnSuccess(result);
    }

    /**
     * 查看统一商品的条码是否重复
     *
     * @param barCode
     * @param goodsId
     * @return
     */
    public TbBizPlaceGoodsCommon checkCommonBarCode(String barCode, String goodsId) {
        TbBizPlaceGoodsCommonExample example = new TbBizPlaceGoodsCommonExample();
        TbBizPlaceGoodsCommonExample.Criteria criteria = example.createCriteria();
        if (barCode != null) {
            criteria.andBarCodeEqualTo(barCode);
        }
        if (goodsId != null) {
            criteria.andGoodsIdEqualTo(goodsId);
        }
        criteria.andIsDeleteEqualTo(0);
        List<TbBizPlaceGoodsCommon> list = tbBizPlaceGoodsCommonMapper.selectByExample(example);
        if (list != null && list.size() > 0) {
            return list.get(0);
        } else {
            return null;
        }
    }

    /**
     * 查看统一商品的编号是否重复
     *
     * @param goodsCode
     * @param goodsId
     * @return
     */
    public TbBizPlaceGoodsCommon checkCommonGoodsCode(String goodsCode, String goodsId) {
        TbBizPlaceGoodsCommonExample example = new TbBizPlaceGoodsCommonExample();
        TbBizPlaceGoodsCommonExample.Criteria criteria = example.createCriteria();
        if (goodsCode != null) {
            criteria.andGoodsCodeEqualTo(goodsCode);
        }
        if (goodsId != null) {
            criteria.andGoodsIdEqualTo(goodsId);
        }
        criteria.andIsDeleteEqualTo(0);
        List<TbBizPlaceGoodsCommon> list = tbBizPlaceGoodsCommonMapper.selectByExample(example);
        if (list != null && list.size() > 0) {
            return list.get(0);
        } else {
            return null;
        }
    }

    /**
     * （统一库）商品名称相同时，商品规格不能重复
     *
     * @param goodsName
     * @param goodsStandard
     * @param goodsId
     * @return
     */
    public TbBizPlaceGoodsCommon checkCommonGoodsStandard(String goodsName,String goodsStandard, String goodsId) {
        TbBizPlaceGoodsCommonExample example = new TbBizPlaceGoodsCommonExample();
        TbBizPlaceGoodsCommonExample.Criteria criteria = example.createCriteria();
        if (goodsName != null) {
            criteria.andGoodsNameEqualTo(goodsName);
        }
        if (goodsStandard != null) {
            criteria.andGoodsStandardEqualTo(goodsStandard);
        }
        if (goodsId != null) {
            criteria.andGoodsIdEqualTo(goodsId);
        }
        criteria.andIsDeleteEqualTo(0);
        List<TbBizPlaceGoodsCommon> list = tbBizPlaceGoodsCommonMapper.selectByExample(example);
        if (list != null && list.size() > 0) {
            return list.get(0);
        } else {
            return null;
        }
    }
    /**
     * 商品名称相同时，商品规格不能重复
     *
     * @param goodsName
     * @param goodsStandard
     * @param goodsId
     * @param placeId
     * @return
     */
    public TbBizPlaceGoodsInfo checkGoodsStandard(String goodsName,String goodsStandard, String goodsId,Integer placeId) {
        TbBizPlaceGoodsInfoExample example = new TbBizPlaceGoodsInfoExample();
        TbBizPlaceGoodsInfoExample.Criteria criteria = example.createCriteria();
        if (goodsName != null) {
            criteria.andGoodsNameEqualTo(goodsName);
        }
        if (goodsStandard != null) {
            criteria.andGoodsStandardEqualTo(goodsStandard);
        }
        if (goodsId != null) {
            criteria.andGoodsIdEqualTo(goodsId);
        }
        if (placeId != null) {
            criteria.andPlaceIdEqualTo(placeId);
        }
        criteria.andIsDeleteEqualTo(0);
        List<TbBizPlaceGoodsInfo> list = tbBizPlaceGoodsInfoMapper.selectByExample(example);
        if (list != null && list.size() > 0) {
            return list.get(0);
        } else {
            return null;
        }
    }
    /**
     * （统一库）校验传入参数
     *
     * @param reqPlaceGoodsCommonVo
     * @return
     */
    public APIResponse<?> checkGoodsCommon(ReqPlaceGoodsCommonVo reqPlaceGoodsCommonVo) {
        if (StringUtils.isEmpty(reqPlaceGoodsCommonVo.getGoodsCode())) {
            return APIResponse.returnFail("商品编号不能为空");
        }
        if (StringUtils.isEmpty(reqPlaceGoodsCommonVo.getGoodsName())) {
            return APIResponse.returnFail("商品名称不能为空");
        }
        if (StringUtils.isEmpty(reqPlaceGoodsCommonVo.getOneLevelId())) {
            return APIResponse.returnFail("请选择一级类别");
        }
        if (StringUtils.isEmpty(reqPlaceGoodsCommonVo.getTwoLevelId())) {
            return APIResponse.returnFail("请选择二级类别");
        }
        if (StringUtils.isEmpty(reqPlaceGoodsCommonVo.getBarCode())) {
            return APIResponse.returnFail("商品条码不能为空");
        }
        if (StringUtils.isEmpty(reqPlaceGoodsCommonVo.getGoodsUnit())) {
            return APIResponse.returnFail("商品单位不能为空");
        }
        if (StringUtils.isEmpty(reqPlaceGoodsCommonVo.getGoodsStandard())) {
            return APIResponse.returnFail("商品规格不能为空");
        }

        if (StringUtils.isEmpty(reqPlaceGoodsCommonVo.getGuideOriginPrice())) {
            return APIResponse.returnFail("商品指导散客价不能为空");
        }
        if (StringUtils.isEmpty(reqPlaceGoodsCommonVo.getGuideMemberPrice())) {
            return APIResponse.returnFail("商品指导会员价不能为空");
        }
        if (StringUtils.isEmpty(reqPlaceGoodsCommonVo.getGuideCostPrice())) {
            return APIResponse.returnFail("商品指导成本价不能为空");
        }
        return null;
    }

    /**
     * 校验传入参数
     *
     * @param reqPlaceGoodsVo
     * @return
     */
    public APIResponse<?> checkGoodsInfo(ReqPlaceGoodsVo reqPlaceGoodsVo) {
        if (StringUtils.isEmpty(reqPlaceGoodsVo.getBarCode())) {
            return APIResponse.returnFail("商品条码不能为空");
        }
        if (StringUtils.isEmpty(reqPlaceGoodsVo.getGoodsCode())) {
            return APIResponse.returnFail("商品编号不能为空");
        }
        if (StringUtils.isEmpty(reqPlaceGoodsVo.getName())) {
            return APIResponse.returnFail("商品名称不能为空");
        }
        if (StringUtils.isEmpty(reqPlaceGoodsVo.getSalePrice())) {
            return APIResponse.returnFail("商品售价不能为空");
        }
        if (StringUtils.isEmpty(reqPlaceGoodsVo.getMemberPrice())) {
            return APIResponse.returnFail("商品会员价不能为空");
        }
        if (!StringUtils.isEmpty(reqPlaceGoodsVo.getBarCode())) {
            TbBizPlaceGoodsInfo infoVo = this.checkBarCode(reqPlaceGoodsVo.getPlaceId(), reqPlaceGoodsVo.getBarCode(), null);
            if (infoVo != null) {
                return APIResponse.returnFail("已经添加该商品条码的商品！");
            }
        }
//        //判断导入的商品跟以前录入商品的有没重复
//        TbBizPlaceGoodsInfoExample example = new TbBizPlaceGoodsInfoExample();
//        TbBizPlaceGoodsInfoExample.Criteria criteria = example.createCriteria();
//        criteria.andGoodsNameEqualTo(reqPlaceGoodsVo.getName().trim());
//        criteria.andPlaceIdEqualTo(reqPlaceGoodsVo.getPlaceId());
//        criteria.andIsDeleteEqualTo(0);
//        List<TbBizPlaceGoodsInfo> list = tbBizPlaceGoodsInfoMapper.selectByExample(example);
//        if (list != null && list.size() > 0) {
//            return APIResponse.returnFail("'" + list.get(0).getGoodsName() + "'" + " " + "商品名称已经存在:");
//        }
        if (!StringUtils.isEmpty(reqPlaceGoodsVo.getGoodsStandard())) {
            TbBizPlaceGoodsInfo infoVo = this.checkGoodsStandard(reqPlaceGoodsVo.getName().trim(),reqPlaceGoodsVo.getGoodsStandard().trim(),null,reqPlaceGoodsVo.getPlaceId());
            if (infoVo != null) {
                return APIResponse.returnFail("已经添加有同样商品名称,同样规格的商品！");
            }
        }
        return null;
    }

    @Override
    public List<TbBizPlaceGoodsTypeCommon> getTypeCommonByParentLevel(@Param("map") Map<String, Object> map) {
        //一级二级分类联动，根据一级分类id或二级分类id获取对应的类型
        String oneLevelId = MapUtils.getString(map,"oneLevelId");
        String twoLevelId = MapUtils.getString(map,"twoLevelId");
        String placeId = MapUtils.getString(map,"placeId");
        if(StringUtils.isEmpty(placeId)){
            TbBizPlaceGoodsTypeCommonExample example = new TbBizPlaceGoodsTypeCommonExample();
            TbBizPlaceGoodsTypeCommonExample.Criteria criteria = example.createCriteria();
            if(oneLevelId!=null){
                if(!"".equals(oneLevelId)){
                    criteria.andLevelEqualTo(Integer.parseInt(oneLevelId));
                }
                List<TbBizPlaceGoodsTypeCommon> list = tbBizPlaceGoodsTypeCommonMapper.selectByExample(example);
                return list;
            }
            if(twoLevelId!=null){
                if(!"".equals(twoLevelId)){
                    criteria.andIdEqualTo(Integer.parseInt(twoLevelId));
                }
                List<TbBizPlaceGoodsTypeCommon> list = tbBizPlaceGoodsTypeCommonMapper.selectByExample(example);
                return list;
            }
            return null;
        }else{

            List<TbBizPlaceGoodsTypeCommon> list = vPlaceGoodsMapper.getGoodsLevels(map);

            return list;
        }
    }


    /**
     * 批量入库
     * @param reqPlaceGoodsVo
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public APIResponse insertInventoryRecordBatch(ReqPlaceGoodsVo reqPlaceGoodsVo) {
        String inputInventoryCode = PlaceUtil.getPlaceInventoryCode(PlaceConstants.PLACE_INPUT_INVENTORY_CODE);
        List<ReqPlaceGoodsVo> list = reqPlaceGoodsVo.getGoodsList();
        if(list!=null&&list.size()>0){
            for(ReqPlaceGoodsVo r : list){
                if (StringUtils.isEmpty(r)) {
                    APIResponse.returnFail("参数不能为空");
                }
                if (r.getGoodsCount() == null) {
                    return APIResponse.returnFail("入库数量不能为空！");
                }
                if (r.getGoodsCount().equals(0)) {
                    return APIResponse.returnFail("入库数量不能为0！");
                }
                if(r.getCostTotalPrice()==null){
                    return APIResponse.returnFail("入库成本总额不能为空！");
                }
                insertInventoryRecordMethod(r,inputInventoryCode,reqPlaceGoodsVo.getBatchRemark(),reqPlaceGoodsVo.getGoodsBill(),reqPlaceGoodsVo.getSupplierName(),reqPlaceGoodsVo.getSupplierId());
            }
            return APIResponse.returnSuccess("批量入库成功");
        }
        return APIResponse.returnFail("批量入库失败，请添加商品！");
    }

    /**
     * 批量盘点库存
     * @param reqPlaceGoodsVo
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public APIResponse checkGoodsInventoryBatch(ReqPlaceGoodsVo reqPlaceGoodsVo) {
        String checkInventoryCode = PlaceUtil.getPlaceInventoryCode(PlaceConstants.PLACE_CHECK_INVENTORY_CODE);
        String batchRemark = reqPlaceGoodsVo.getBatchRemark();
        List<ReqPlaceGoodsVo> list = reqPlaceGoodsVo.getGoodsList();
        if(list!=null&&list.size()>0){
            for(ReqPlaceGoodsVo r : list){
                if (StringUtils.isEmpty(r)) {
                    return APIResponse.returnFail("参数不能为空");
                }
                if(r.getAfterCheckInventory()==null){
                    return APIResponse.returnFail("实际盘点库存不能为空");
                }
                checkGoodsInventoryMethod(r,checkInventoryCode,batchRemark);
            }
            return APIResponse.returnSuccess("批量盘点库存成功");
        }
        return APIResponse.returnFail("批量盘点失败，请添加商品！");
    }

    /**
     * 上下架
     * @param reqPlaceGoodVo
     * @return
     */
    public APIResponse<?> updownGoods(ReqPlaceGoodsVo reqPlaceGoodVo) {
        TbBizPlaceGoods vo = this.getGoodsInfoByid(reqPlaceGoodVo);
        TbBizPlaceGoods goods = new TbBizPlaceGoods();
        goods.setId(reqPlaceGoodVo.getId());
        if (vo != null) {
            if (!vo.getStatus().equals(reqPlaceGoodVo.getStatus())) {
                goods.setUpDownTime(new Date());
                goods.setStatus(reqPlaceGoodVo.getStatus());
           }
       }
        tbBizPlaceGoodsMapper.updateByPrimaryKeySelective(goods);
        return APIResponse.returnSuccess("上下架成功");
    }

    @Override
    public APIResponse<?> getGoodsInfoByBarCode(ReqPlaceGoodsVo reqPlaceGoodVo) {
        if(reqPlaceGoodVo.getBarCode()!=null){
            RespPlaceGoodsVo respPlaceGoodsVo  = vPlaceGoodsMapper.getGoodsInfoByBarCode(reqPlaceGoodVo);

            if(respPlaceGoodsVo!=null){
                return APIResponse.returnSuccess(respPlaceGoodsVo);
            }else{
                return APIResponse.returnFail("没有该条码的商品");
            }
        }
        return APIResponse.returnFail("请输入商品条码");
    }

    @Override
    public APIResponse<?> insertGoodsAndList(@Param("map") Map<String, Object> map) {
        Integer placeId = MapUtils.getInteger(map,"placeId");
        TbBizPlaceGoodsInfoExample example = new TbBizPlaceGoodsInfoExample();
        example.createCriteria().andPlaceIdEqualTo(placeId);
        List<TbBizPlaceGoodsInfo> list0 = tbBizPlaceGoodsInfoMapper.selectByExample(example);
        Integer pageNum = Constants.DEFAULT_PAGE_NUM;
        Integer pageSize = Constants.DEFAULT_PAGE_SIZE;
        Integer reqPageNum = MapUtils.getInteger(map, "pageNum");
        if (!StringUtils.isEmpty(MapUtils.getInteger(map, "pageSize"))) {
            pageSize = MapUtils.getInteger(map, "pageSize");
        }
        if (!StringUtils.isEmpty(MapUtils.getInteger(map, "pageNum"))) {
            pageNum = MapUtils.getInteger(map, "pageNum") * pageSize;
        }
        map.put("pageNum", pageNum);
        map.put("pageSize", pageSize);
        if(!StringUtils.isEmpty(MapUtils.getInteger(map, "commonFlag"))){
            String flag = MapUtils.getString(map, "commonFlag");
            map.put("commonFlag",flag);
        }
        Integer total = vPlaceGoodsMapper.countCoodsCommonList(map);
        List<RespPlaceGoodsCommonVo> list = vPlaceGoodsMapper.getGoodsCommonList(map);
        if(list0!=null&&list!=null){
            for(int i = 0;i<list0.size();i++){
                for (int j = 0;j<list.size();j++){
                    if(list.get(j).getGoodsCode().equals(list0.get(i).getGoodsCode())){
                        list.get(j).setFlag(1);
                    }
                }
            }
        }

        for(RespPlaceGoodsCommonVo respPlaceGoodsCommonVo : list){
            String oneId = respPlaceGoodsCommonVo.getOneLevelTypeId()+"";
            String oneName = "";
            List<Dict> listDict = this.getOneLevel(null);
            for(Dict dict : listDict){
                if(oneId.equals(dict.getDataKey())){
                    oneName=dict.getDataValue();
                }
            }
            respPlaceGoodsCommonVo.setOneLevelName(oneName);
        }
        PageObj<List<RespPlaceGoodsCommonVo>> result = PageObj.create(total, reqPageNum, pageSize, list);

        return APIResponse.returnSuccess(result);
    }
}

